c++ - C++中与Arduino的串行通信超时

标签 c++ serial-port arduino

下面的代码是我用来从我的 Arduino 发送和接收信息的代码。我的问题是当 Arduino 第一次插入时。读取它挂起,因为命令没有返回任何东西,因为那里什么都没有,所以我的整个程序崩溃了。如何为导致问题的读取函数添加超时,即 arduino->ReadLine();?这样它会在一秒钟后继续吗?

#include "stdafx.h"
#include <iostream>

using namespace System;
using namespace System::IO::Ports;

int main(int argc, char* argv[])
{
    using namespace std;

    String^ portName;
    int baudRate=9600;

    portName="COM4";
    // Arduino settings.
    SerialPort^ arduino;

    arduino = gcnew SerialPort(portName, baudRate);
    // Open port.
    try
    {
        arduino->Open();
        {
            if (strcmp(argv[1],"-send")==0) {
                String^ command = gcnew String(reinterpret_cast<const char*>(argv[2]));
                if (String::Compare(command,"int6")==0) {
                    arduino->Write("^");
                }
                else
                    arduino->Write(command);
            }
            if(strcmp(argv[1],"-get")==0) {
                String^ command = gcnew String(reinterpret_cast<const char*>(argv[2]));
                arduino->WriteLine(command);
                String^ result = arduino->ReadLine();
                Console::Write(result);
            }
        }

最佳答案

设置arduino->ReadTimeout = duration_in_ms 然后捕获TimeoutException

关于c++ - C++中与Arduino的串行通信超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5723949/

相关文章:

boost - 如何使用 asio 执行非阻塞读取?

linux - cu 不发送 TTY 响应到 bash 输出

c++ - 如何在C++中将 float 组转换为字节数组(Arduino)

c++ - 包含函数的 C 宏

Arduino 和 RC 发射器

c++ - 如何导入将 [c++] 类导入 [objective-c] 类的 [objective-c++] 类?

c++ - 使用未分配的内存没有错误?

c++ - 在特定的 Unicode 路径中创建文件

c++ - 使用二进制搜索的模板递归

serial-port - 有什么好的、免费的用于逆向工程的串行端口监视器?