Boost :: Asio串行读/写打开:参数不正确

问题描述 投票:0回答:1

我非常了解C ++,并且正在尝试使用Visual Studio读取/写入串行端口。我正在尝试使用Boost :: Asio,但是我总是遇到类似的错误。当我尝试运行下面的代码时,我得到“ 错误:打开:参数不正确”。

为了确保串行端口和我的设备正常工作,我使用了另一个应用程序。我能够读/写没有问题。测试后,我关闭了我的应用程序,以免造成任何问题。

UPDATE:通过使用虚拟串行端口仿真器(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 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
1个回答
0
投票

我通过更改使它起作用

dcb.BaudRate = 0; 

dcb.BaudRate = 9600; 

在include / boost / asio / detail / impl / win_iocp_serial_port_service.ipp,即boost::system::error_code win_iocp_serial_port_service::open中,这是一个已知问题的解决方法,在boost :: asio中有开放合并请求,请参见https://github.com/boostorg/asio/issues/280https://github.com/boostorg/asio/pull/273

您仍可以通过打开后使用便携式选项来使用其他波特设置,但是Windows不会接受0,如作者希望的那样“使用以前使用的波特”。

希望它会被更改,我将在这篇文章中发布boost版本,届时它将再次运行,而无需再次热修补boost实现。

© www.soinside.com 2019 - 2024. All rights reserved.