Boost串口通信 boost::asio::serial_port基本使用
boost库有一个asio,支持串口通信。
步骤:
1、产生一个boost::asio::io_service(前摄模式,类似于完成端口,不过,可以针对不同IO对象)
2、构造一个boost::asio::serial_port,有两种方法:
boost::asio::serial_port m_serialPort(m_IoService, "COM1");//或者boost::asio::serial_port m_serialPort(m_IoService);m_serialPort.open("COM1");
例如:
using namespace boost::asio;io_service iosev;serial_port sp(iosev, "/dev/ttyUSB0");
注意这种方式打开,如果串口没有准备好,会导致程序抛异常,导致程序崩溃,所以应该要try{} catch包含,或者使用如下的方式
boost::system::error_code ec;serial_port sp(iosev);m_serialPort.open("COM1", ec);if (ec) return;//还可以用另一种方式try{boost::asio::serial_port m_serialPort(m_IoService);m_serialPort.open("COM1");}catch (exception& err){}
3、设置串口参数:波特率、奇偶校验 位、停止位、字符大小和流量控制,通过set_option方法
boost::asio::serial_port::baud_rate //波特率boost::asio::serial_port::parity//奇偶校验,可以为serial_port::parity::none / odd / even。boost::asio::serial_port::flow_control//流量控制, 可以为serial_port::flow_control::type,enum类型,可以是none software hardwareboost::asio::serial_port::stop_bits//停止位,可以为serial_port::stop_bits::one /onepointfive /twoboost::asio::serial_port::character_size //字符大小
4、数据读写
read_somewrite_someasync_read_someasync_write_some
5、同步读取例子
io_service iosev;boost::system::error_code ec;serial_port sp(iosev);sp.open("COM1", ec);if (ec) return;sp.set_option(serial_port::baud_rate(9600));sp.set_option(serial_port::flow_control(serial_port::flow_control::none));sp.set_option(serial_port::parity(serial_port::parity::none));sp.set_option(serial_port::stop_bits(serial_port::stop_bits::one));sp.set_option(serial_port::character_size(8));std::string strCompleteMsg;boost::asio::streambuf content_sb;int bytes = 0;while (1){strCompleteMsg = "";bytes = 0;while (strCompleteMsg.find("\r\n") == std::string::npos){bytes += boost::asio::read(sp, content_sb, boost::asio::transfer_exactly(1), ec);if (ec) break;boost::asio::streambuf::const_buffers_type cont_bufs = content_sb.data();strCompleteMsg = std::string(boost::asio::buffers_begin(cont_bufs), boost::asio::buffers_begin(cont_bufs) + bytes);}}
参考
/kernel0815/p/3624632.html