Boost ASIO serial_port

Source: Internet
Author: User

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));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.