【发布时间】:2019-10-28 11:52:28
【问题描述】:
我非常了解 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;
};
【问题讨论】:
标签: c++ visual-studio boost-asio