http://blog.csdn.net/jwybobo2007/article/details/7019061
以下是serial_port同步讀寫序列槽裝置的示例代碼:
[cpp] view plain copy
- #include <iostream>
- #include <boost/asio.hpp>
- #include <boost/bind.hpp>
- using namespace std;
- int main(int argc, char* argv[])
- {
- try
- {
- boost::asio::io_service io;
- boost::asio::serial_port sp(io, "COM1");
- sp.set_option(boost::asio::serial_port::baud_rate(38400));
- sp.set_option(boost::asio::serial_port::flow_control());
- sp.set_option(boost::asio::serial_port::parity());
- sp.set_option(boost::asio::serial_port::stop_bits());
- sp.set_option(boost::asio::serial_port::character_size(8));
- boost::asio::write(sp, boost::asio::buffer("\n", 1));
- char buf[101];
- boost::system::error_code err;
- while (true)
- {
- size_t ret = sp.read_some(boost::asio::buffer(buf, 100), err);
- if (err)
- {
- cout << "read_some Error: " << err.message() << endl;
- break;
- }
- else
- {
- buf[ret] = '\0';
- cout << buf;
- }
- }
- io.run();
- }
- catch (exception& err)
- {
- cout << "Exception Error: " << err.what() << endl;
- }
- getchar();
- return 0;
- }
如果想進行讀寫逾時控制的話,寫需要适用異步寫的方式,另外加入定時代碼:
[cpp] view plain copy
- boost::asio::deadline_timer timer(io);
- timer.expires_from_now(boost::posix_time::millisec(60000));