天天看點

boost asio serial_port 讀寫序列槽

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

如果想進行讀寫逾時控制的話,寫需要适用異步寫的方式,另外加入定時代碼:

[cpp]  view plain copy

  1. boost::asio::deadline_timer timer(io);  
  2. timer.expires_from_now(boost::posix_time::millisec(60000));