Social Nerwork

Telephone us on: +353 87 223 6429 or email us using:
Telephone us on: +353 87 223 6429 or email us using:

boost C++ read from serial port with timeout example

If you are doing any serial port communications these days in C++ and would like your code to be portable, then you are probably using boost’s asio::serial_port class.


One complication with using serial_port (and boost::asio more generally) is that it doesn’t provide a direct facility to allow synchronous blocking reads to time-out and return if no data arrives within a specified time period. Here is a little example that tries to read a character from COM3 (on windows..)



In this example read() will block forever if no data arrives to the serial port, this is not always what you want, especially when dealing with possibly noisy or unreliable rs232 communication.


In order to take advantage of read time-outs you have to issue asynchronous reads and incorporate a deadline_timer which will cancel the read after a specified time, i.e. if the read hasn’t received the data it was expecting before the deadline_timer expires, then it will be cancelled.


Using asynchronous IO in boost is a bit involved and it can be quite quite messy, so I have written small class called blocking_reader which will block while trying to read a single character, and will time out if a character hasn’t been received in a specified number of milliseconds. It can be used like this:


The above code isn’t the most sensible or efficient but it shows the use of blocking_reader, which in this case times out reads after 500ms.


You open the serial_port as normal and then pass it to blocking_reader’s constructor along with a timeout value. You then use blocking_reader.read_char() to read a single character. If the read times out then read_char() will return false (otherwise it will return true!)


The code for blocking_reader can be downloaded from here, I have also included it below:


  1. Fer 5 years ago

    Thanks! It is just what I was looking for.


  2. Mariusz 2 years ago

    Could someone help me to compile it please?

    Thank you and best regards

  3. Mariusz 2 years ago


    using namespace boost;

    char read_char() {
    asio::io_service io;
    asio::serial_port port(io);“COM3”);

    char c;

    // Read 1 character into c, this will block
    // forever if no character arrives.
    asio::read(port, asio::buffer(&c,1));


    return c;

  4. Mariusz 2 years ago

    And this is when I’m trying to compile the second code:

  5. Mariusz 2 years ago

    Could you please help me?

    Thank you and best regards

  6. Stephen Braithwaite 2 years ago

    Hi there,
    Do you give permission to use this code?

    • Kevin 2 years ago

      Hi Stephen, feel free to use the code if you find it useful (at your own risk!) Thanks for asking. K.

  7. shamsher 1 year ago

    thanks a lot friend