15

So I've been trying to learn the boost::asio stuff to communicate to a serial device using RS232. The documementation is sparse and the examples are non-existent. Can't figure out exactly how to communicate with the device. The device can't send data so all I need to do is write, but other projects require actual back and forth communication so help with that would be appreciated. What code I have so far follows.

#include <boost/asio/serial_port.hpp>
using namespace::boost::asio;

int main()
{
    io_service io;
    serial_port port( io, "COM3" );
    port.set_option( serial_port_base::baud_rate( 19200 ) );

    unsigned char commands[4] = { 1, 128, 240, 0 };

    // write the commands to the device

    return 0;
}

In short: need help with the io part of the serial_port.

3 Answers 3

17

In addition to the baud rate, you may also need to set other options like: character_size, flow_control, parity and stop_bits. To write your data to the serial port you can do the following:

boost::asio::write(port, boost::asio::buffer(commands, 4));

The libraries acceptance of buffer types is very flexible and you may want to read further on that topic here: Buffers.

1
  • Thanks, was mostly overwhelmed with the number of options and needed somewhere to get started. I lucked out because the defaults values for everything except baud rate are what the board uses. Nov 6, 2008 at 18:13
16

Thanks to the help from here and other places I got it working. Wrote a small program that might help some people figure out the boost serial port stuff as well.

boostserialportdemo.cpp

2
  • 1
    the linux version of your demo should use /dev/ttyS2. Linux devices use 0 based numbering
    – deft_code
    Oct 14, 2009 at 14:50
  • I'm getting 404 on that page. Would you mind uploading it somewhere else? Thanks. Dec 6, 2011 at 12:21
0

If you are wondering why his example gives a compile error, change CSIZE to C_SIZE on both lines. This is probably the only good example program on the web.
Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.