现在的位置: 首页 > 综合 > 正文

boost asio serial_port 读写串口

2013年08月15日 ⁄ 综合 ⁄ 共 1505字 ⁄ 字号 评论关闭

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

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

  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. }  


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

  1. boost::asio::deadline_timer timer(io);  
  2. timer.expires_from_now(boost::posix_time::millisec(60000));  
【上篇】
【下篇】

抱歉!评论已关闭.