c++ - Boost::Asio Serial Read/Write open: 参数不正确
问题描述
我对 C++ 有非常基本的了解,我正在尝试使用 Visual Studio 读/写串行端口。我正在尝试使用Boost::Asio但我总是遇到类似的错误。当我尝试运行下面的代码时,我得到“错误:打开:参数不正确”。
为了确保串行端口和我的设备正常工作,我使用了另一个应用程序。我可以毫无问题地读/写。测试后,我关闭了我的应用程序,以免造成任何问题。
更新:通过使用虚拟串行端口仿真器(VSPE),我创建了一对端口(COM1 和 COM2)。我在 C++ 中使用了 COM1,在 RealTerm 中使用了 COM2。通过这个,我成功地用我的代码读/写了数据,没有任何问题。但是当我尝试访问 COM6 时,我仍然遇到同样的错误。连接到该端口的 FPGA 并且我还使用 RealTerm 测试了能够读/写的 FPGA,这意味着可以按预期工作。所以,看起来我的问题是访问 COM6 端口。寻求您的建议。
我愿意接受任何建议。
#include <iostream>
#include "SimpleSerial.h"
using namespace std;
using namespace boost;
int main(int argc, char* argv[])
{
try {
SimpleSerial serial("COM6", 115200);
serial.writeString("Hello world\n");
cout << serial.readLine() << endl;
}
catch (boost::system::system_error & e)
{
cout << "Error: " << e.what() << endl;
return 1;
}
}
我在网上找到了这个 SimpleSerial Class 并尝试制作基本应用程序。
class SimpleSerial
{
public:
/**
* Constructor.
* \param port device name, example "/dev/ttyUSB0" or "COM4"
* \param baud_rate communication speed, example 9600 or 115200
* \throws boost::system::system_error if cannot open the
* serial device
*/
SimpleSerial(std::string port, unsigned int baud_rate)
: io(), serial(io, port)
{
serial.set_option(boost::asio::serial_port_base::baud_rate(baud_rate));
}
/**
* Write a string to the serial device.
* \param s string to write
* \throws boost::system::system_error on failure
*/
void writeString(std::string s)
{
boost::asio::write(serial, boost::asio::buffer(s.c_str(), s.size()));
}
/**
* Blocks until a line is received from the serial device.
* Eventual '\n' or '\r\n' characters at the end of the string are removed.
* \return a string containing the received line
* \throws boost::system::system_error on failure
*/
std::string readLine()
{
//Reading data char by char, code is optimized for simplicity, not speed
using namespace boost;
char c;
std::string result;
for (;;)
{
asio::read(serial, asio::buffer(&c, 1));
switch (c)
{
case '\r':
break;
case '\n':
return result;
default:
result += c;
}
}
}
private:
boost::asio::io_service io;
boost::asio::serial_port serial;
};
解决方案
我通过改变让它工作
dcb.BaudRate = 0;
至
dcb.BaudRate = 9600;
在 include/boost/asio/detail/impl/win_iocp_serial_port_service.ipp ieboost::system::error_code win_iocp_serial_port_service::open
中,这是一个已知问题的解决方法,在 boost::asio 中有开放的合并请求,请参阅
https://github.com/boostorg/asio/issues /280和
https://github.com/boostorg/asio/pull/273。
您仍然可以使用其他波特率设置,通过在打开后使用可移植选项,但 Windows 不会接受 0 以希望“使用之前使用的波特率”,正如作者所希望的那样。
希望它会有所改变,我将在这篇文章中发布 boost 版本,届时它将在没有热补丁 boost 实现的情况下再次工作。