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