The following is an example code of serial_port synchronous reading/writing to a serial port device:
#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;}
If you want to control the read/write timeout, the write method must be asynchronous. In addition, the scheduled code is added:
boost::asio::deadline_timer timer(io);timer.expires_from_now(boost::posix_time::millisec(60000));timer.async_wait(boost::bind(&boost::asio::serial_port::cancel, &sp));