Boost logo

Boost Users :

Subject: Re: [Boost-users] Can someone provide an Asio Serial Port example?
From: Michael Caisse (boost_at_[hidden])
Date: 2010-01-21 02:33:27


Jeff wrote:
> I would like to use Asio to connect to a microcontroller to send and read from,
> but there are no serial_port samples available.
>
> For instance, I would like to type an ‘a’ into the keyboard and have the
> microcontroller return 1. The microcontroller is already programmed for this
> but I need to create an interface for it.
>
> A sample that does this or any working sample at all would be sincerely
> appreciated.
>
> Thank you,
>
> Jeff
>
>

Hi Jeff -

Using the asio serial port is just like using the socket after you
have one opened and going.

To get things going:

Construct the serial port with the associated io_service as
with other ASIO services...

   asio::serial_port port( io_service );

Next, open the device and setup various options. I have found
that the defaults among various OS's for the asio serial port
differ. It can create real headaches so I initialize everything
that I like:

   port.open( "/dev/ttyUSB0" ); // or whatever the device might be

   if( !port.is_open() ){ // do something clever if the open failed }

   typedef boost::asio::serial_port_base asio_serial;

   port.set_option( asio_serial::baud_rate( baud ) );
   port.set_option( asio_serial::flow_control( asio_serial::flow_control::none ) );
   port.set_option( asio_serial::parity( asio_serial::parity::none ) );
   port.set_option( asio_serial::stop_bits( asio_serial::stop_bits::one ) );
   port.set_option( asio_serial::character_size( 8 ) );

Then just use the port as you would a socket. For example,

   port.async_read_some( asio::buffer( in_message, MAX_MESSAGE_SIZE ),
                         boost::bind( &my_client::read_done,
                                      shared_from_this(),
                                      asio::placeholders::error,
                                      asio::placeholders::bytes_transferred ) );

HTH,
michael

-- 
----------------------------------
Michael Caisse
Object Modeling Designs
www.objectmodelingdesigns.com

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net