如何在程序的中间等待串口的输入
How to wait for input from the serial port in the middle of a program
我正在写一个程序来控制与卫星通信的铱调制解调器。在每个AT命令发送后,modem发送一个应答(根据命令的不同)来表示命令成功。
现在我已经实现了它,以便程序在每个命令传输到调制解调器之间只等待10秒,但这有点冒险,因为它不允许在命令未成功解释的情况下进行错误处理。我知道如何读取串行输入的唯一方法是使用while(fgets( , ,))
,所以我想知道我如何能够让程序等待调制解调器通过串行端口的回复,并在下一个命令发送之前检查它是什么,而不是有统一的延迟。
我用的是linux操作系统。
FILE *out = fopen(portName.c_str(), "w");//sets the serial port
for(int i =0; i<(sizeof(messageArray)/sizeof(messageArray[0])); i++)
{
//creates a string with the AT command that writes to the module
std::string line1("AT+SBDWT=");
line1+=convertInt( messageArray[i].numChar);
line1+=" ";
line1+=convertInt(messageArray[i].packetNumber);
line1+=" ";
line1+=messageArray[i].data;
line1+=std::string("rn");
//creates a string with the AT command that initiates the SBD session
std::string line2("AT+SBDI");
line2+=std::string("rn");
fputs(line1.c_str(), out); //sends to serial port
usleep(10000000); //Pauses between the addition of each packet.
fputs(line2.c_str(), out); //sends to serial port
usleep(10000000);
}
对串行端口对应的文件描述符使用select或poll,当描述符准备好读取时将返回。
像这样:
int fd = fileno(stdin); /* If the serial port is on stdin */
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
struct timeval timeout = { 10, 0 }; /* 10 seconds */
int ret = select(fd+1, &fds, NULL, NULL, &timeout);
/* ret == 0 means timeout, ret == 1 means descriptor is ready for reading,
ret == -1 means error (check errno) */
为了尽可能接近你的模型,你可以做几件事:
1)使用普通文件句柄(通过open())。然后,您将使用read()和write()与串行端口通信。
2)使用上面的1,然后让你使用select来查看是否有东西准备写入或读取。
如果您的程序有其他事情要做,这也允许您将与调制解调器的通信移动到另一个线程…
我最近用高频无线电调制解调器做了一些非常类似的事情,并使用Boost ASIO库进行串口通信。
相关文章:
- 为什么我要从串口读取垃圾?
- Boost Asio SerialPort。无法创建并打开串口服务
- 如何在QtWidget中使用c++串口发送数据
- 如何插入十六进制值并发送到串口?
- 串口打开返回 EAGAIN
- QT 5.10.1 串口不发送,为什么?
- 通过串口发送后无法获取原始值
- C++ / RS232C 串口 / 事件回调异步读取缓冲区 / 不使用线程
- 串口读取功能的通信超时和线程不超时
- QT 5.7 串口读取速度很慢
- 串口通信
- 为什么Qt(4.8)串口(qextserialport)分两部分从设备读取数据
- 将C++串口奇偶校验更改代码从 Linux 移植到 Windows
- qt串口未打开
- 有没有一个跨平台的c++串口库可以枚举端口
- Qt串口,当我写的时候,我看不懂我写的东西
- 是否可以检查串口是空闲还是占用
- 当其他线程正在等待读取时,写入串口将永远阻塞
- 如何在程序的中间等待串口的输入
- 在Qt中等待数据从串口到达