Boost Windows 2 1 Serial Port

Posted on by admin

In part I 1 of this article, we used Boost libraries under both Windows and Linux to communicate with a GPS receiver connected to a serial port. Boost Asio 2 was used for asynchronous I/O to read data from the receiver in a platform-independent manner, with other Boost libraries in supporting roles.

Usb Serial Port Windows 10

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

2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
#include <boost/asio/serial_port.hpp>
#include 'blocking_reader.h'
usingnamespaceboost;
std::stringread_response(){
asio::io_service io;
port.set_option(asio::serial_port_base::baud_rate(115200));
// A blocking reader for this port that
blocking_reader reader(port,500);
charc;
std::stringrsp;
// read from the serial port until we get a
while(reader.read_char(c)&&c!='n'){
}
if(c!='n'){
throwstd::exception('Read timed out!');
}
Port

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: