【问题标题】:Serial communication timeout in C++ with Arduino使用 Arduino 的 C++ 中的串行通信超时
【发布时间】:2011-04-19 23:32:17
【问题描述】:

下面的代码是我用来从我的 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);
            }
        }

【问题讨论】:

    标签: c++ serial-port arduino


    【解决方案1】:

    设置arduino-&gt;ReadTimeout = duration_in_ms,然后捕获TimeoutException

    【讨论】:

      【解决方案2】:

      除了超时之外,您的代码应该循环直到 SerialPort 的 BytesToRead 属性大于零

      while (arduino->BytesToRead==0) {}
      

      如果在预期的时间范围内没有从 arduino 收到任何内容,您可以跟踪循环的时间并通过用户消息优雅地退出。

      【讨论】:

        猜你喜欢
        • 2017-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多