boost asio serial_port 读写串口

6 篇文章 1 订阅

http://blog.csdn.net/jwybobo2007/article/details/7019061

以下是serial_port同步读写串口设备的示例代码: 

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <boost/asio.hpp>  
  3. #include <boost/bind.hpp>  
  4.   
  5. using namespace std;  
  6.   
  7. int main(int argc, char* argv[])  
  8. {  
  9.     try  
  10.     {  
  11.         boost::asio::io_service io;  
  12.         boost::asio::serial_port sp(io, "COM1");  
  13.   
  14.         sp.set_option(boost::asio::serial_port::baud_rate(38400));  
  15.         sp.set_option(boost::asio::serial_port::flow_control());  
  16.         sp.set_option(boost::asio::serial_port::parity());  
  17.         sp.set_option(boost::asio::serial_port::stop_bits());  
  18.         sp.set_option(boost::asio::serial_port::character_size(8));  
  19.   
  20.         boost::asio::write(sp, boost::asio::buffer("\n", 1));  
  21.   
  22.         char buf[101];  
  23.         boost::system::error_code err;  
  24.         while (true)  
  25.         {  
  26.             size_t ret = sp.read_some(boost::asio::buffer(buf, 100), err);  
  27.             if (err)  
  28.             {  
  29.                 cout << "read_some Error: " << err.message() << endl;  
  30.                 break;  
  31.             }  
  32.             else  
  33.             {  
  34.                 buf[ret] = '\0';  
  35.                 cout << buf;  
  36.             }  
  37.         }  
  38.   
  39.         io.run();  
  40.     }  
  41.     catch (exception& err)  
  42.     {  
  43.         cout << "Exception Error: " << err.what() << endl;  
  44.     }  
  45.   
  46.   
  47.     getchar();  
  48.     return 0;  
  49. }  

如果想进行读写超时控制的话,写需要适用异步写的方式,另外加入定时代码:

[cpp]  view plain copy
  1. boost::asio::deadline_timer timer(io);  
  2. timer.expires_from_now(boost::posix_time::millisec(60000));  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值