C++ 中的串行通信超时与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);
}
}
The code below is what I am using to send and receive information from my 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. How can I add a time-out to the read function, which is 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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
设置 arduino->ReadTimeout =uration_in_ms ,然后捕获 TimeoutException 。
Set
arduino->ReadTimeout = duration_in_ms
and then catchTimeoutException
.除了超时之外,您的代码还应该循环,直到 SerialPort 的 BytesToRead 属性大于零。
您可以跟踪循环了多长时间,如果没有收到任何消息,则使用用户消息优雅地退出arduino 在预期的时间范围内。
In addition to the timeout your code should loop until the
BytesToRead
property of the SerialPort is greater than zeroYou 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.