简体   繁体   English

带有Arduino的C ++中的串行通信超时

[英]Serial communication timeout in C++ with Arduino

The code below is what I am using to send and receive information from my Arduino. 下面的代码是我用来从Arduino发送和接收信息的代码。 My problem is when the Arduino is first plugged in. Reading from it hangs because the command doesn't return anything because there is nothing there yet so my whole program crashes. 我的问题是Arduino首次插入时。由于该命令未返回任何内容(因为还没有任何内容),因此挂起了读取操作,因此整个程序崩溃了。 How can I add a time-out to the read function, which is arduino->ReadLine(); 我该如何添加超时到读取函数,即arduino->ReadLine(); , that causes the issue? ,那会导致问题? That way will it keep going after a second? 这样一秒钟会继续吗?

#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

In addition to the timeout your code should loop until the BytesToRead property of the SerialPort is greater than zero 除了超时外,您的代码还应循环执行,直到SerialPort的BytesToRead属性大于零为止

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

You could keep track of how long you have looped and exit gracefully with a user message if there is nothing received from the arduino within the expected time frame. 如果在预期的时间内没有收到来自arduino的任何信息,则可以跟踪循环的时间并通过用户消息正常退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM