Boost ASIO串行写入十六进制值 [英] Boost ASIO Serial Write Hex values

查看:803
本文介绍了Boost ASIO串行写入十六进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ubuntu通过串行端口与设备通信。所有消息都需要是十六进制值。我在Windows环境中测试了使用白蚁的通信设置,我得到了我所期望的响应。我使用Boost:asio时无法得到任何响应。

I am communicating with a device via a serial port using ubuntu. All the messages need to be hex values. I have tested the communication setup using termite in a Windows environment and I get the responses I am expecting. I cannot get any responses when using Boost:asio though.

以下是我设置串行端口的方法:

Here is how I am setting up my serial port:

boost::asio::serial_port serialPort;
    serialPort.open(portNumber);
    serialPort.set_option(boost::asio::serial_port_base::baud_rate(baudRate));
    serialPort.set_option(boost::asio::serial_port_base::character_size(8));
    serialPort.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
    serialPort.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
    serialPort.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none));

  uint8_t hexValue = message.at(i) >= 'A' ? (message.at(i) - 'A' + 10) : message.at(i) - '0';
  serialPort.write_some(boost::asio::buffer(&hexValue, sizeof(uint8_t)));

b $ b

推荐答案

看起来真的要发送对应于十六进制的二进制 数据 c /。

It looks like really you want to send the binary data that corresponds to the hex-encoded text you have in message.

有许多方法可以让你在猫。我个人从解码整个消息开始。这将始终减少来自十六进制编码大小的消息。

There are many ways to skin that cat. I'd personally start with decoding the whole message. This will always reduce the message from the hex-encoded size. So you can do this inplace, if you want.

较旧的答案

std::string hex2bin(std::string const& s) {
    assert(s.length() % 2 == 0);

    std::string sOut;
    sOut.reserve(s.length()/2);

    std::string extract;
    for (std::string::const_iterator pos = s.begin(); pos<s.end(); pos += 2)
    {
        extract.assign(pos, pos+2);
        sOut.push_back(std::stoi(extract, nullptr, 16));
    }
    return sOut;
}

现在你只需将返回的字符串发送到串口:

Now you simply send the returned string to the serial port:

std::string binary_msg = hex2bin(message);
serialPort.write_some(boost::asio::buffer(binary_msg));

另请参阅全局 http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/reference/write.html 在一个组合操作中写入整个消息。

Also look at the global http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/reference/write.html to write the whole message in one composed operation.

这篇关于Boost ASIO串行写入十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆