提升 asio 串行端口"end of file"

Boost asio serial port "end of file"

本文关键字:of file end 提升 串行端口 asio      更新时间:2023-10-16

我正在尝试读取来自arduino的串行数据,但是当我运行程序时,它只读取缓冲区中的所有数据,即程序启动之前实际发送的数据。然后我终止并显示以下错误:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >'
what():  read: End of file
Aborted (core dumped)

我什至不想要程序执行之前的数据。这是我的 c++ 代码:

#include <iostream>
#include <stdint.h>
#include <boost/asio.hpp>
#include <boost/asio/serial_port.hpp>
using namespace boost;
int main() {
asio::io_service io;
asio::serial_port port(io);
port.open("/dev/ttyUSB0");
port.set_option(asio::serial_port_base::baud_rate(115200));
char d;
while ( true ) {
asio::read(port, asio::buffer(&d, 1));
std::cout << d << std::endl;
}
port.close();
}

据我所知,读取函数应该是阻塞的,所以它会等待下一个输入,对吧?那么它如何到达"文件"的末尾呢?

这就是对我有用的。您需要为串行端口提供最小字符限制才能具有阻止功能。

stty -F /dev/ttyUSB5 115200 line 0 min 1 time 0

编辑:更好的选择似乎只是将端口设置为原始模式。

stty -F /dev/ttyUSB0 raw

所以我发现在以 root 身份运行 Arduino IDE 后,为了允许串行通信,我的程序停止工作,并且出现 EOF 错误。即使在Arduino IDE关闭后,它也无法正常工作,重新启动我的PC也可以使其再次工作。

但Atilla Filiz的回答解决了这个问题。