Issue with asio::serial_port - async_write_some handler isn't firing

Hi,
I'm trying to get a simple application up and running that sends and
receives simple commands through a COM port to an Arduino hooked up to some
sensors. Right now, I'm just trying to send the Arduino a simple command
through a boost::asio::serial_port instance, although at some point I'll
need to start reading from it as well.
At any rate, I think I've got the basic premise down, but for some reason
the WriteComplete function (see code below) isn't being called. After
running the program, the output is:
Open
Sending command '.'
Press any key to continue.
I'm not 100% sure what's going on. The only thing I can think of is that
the boost::asio::buffer(&command, sizeof(command)) statement is wrong. I'm
not very familiar with these libraries, though, so I don't know what I
would replace it with.
I've included the code I'm using in case anyone can help me out.
Thanks,
-Alex
---
#include "stdafx.h"
#include <iostream>
#include

boost::asio::io_service gService; boost::asio::serial_port gPort(gService);
void WriteComplete(const boost::system::error_code& error, std::size_t bytes_transferred) { cout << "Write complete." << endl; gPort.close(); }
int _tmain(int argc, _TCHAR* argv[]) { gPort.open("COM3"); if(!gPort.is_open()) { cout << "Could not open com port." << endl; return 0; } cout << "Open" << endl;
typedef boost::asio::serial_port_base asio_serial;
gPort.set_option( asio_serial::baud_rate( 9600 ) ); gPort.set_option( asio_serial::flow_control( asio_serial::flow_control::none ) ); gPort.set_option( asio_serial::parity( asio_serial::parity::none ) ); gPort.set_option( asio_serial::stop_bits( asio_serial::stop_bits::one ) ); gPort.set_option( asio_serial::character_size( 8 ) );
char command = '.'; cout << "Sending command '" << command << "'" << endl;
gPort.async_write_some( boost::asio::buffer(&command, sizeof(command)), boost::bind( &WriteComplete, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred ) );
cout << "Press any key to continue."; cin.ignore(); cin.get();
return 0; }
Note that the completion handler WriteComplete will never be invoked because you don't call gService.run(). Did you take a look at ASIO docs? http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio.html To make the above code work you can either change async_write() to write(), i.e. write the data synchronously, or call gService.run() instead of cin.get(). Besides, note that you pass an address of a local object to async.operation (async_write_some(buffer(&command, sizeof(command))...), which is dangerous in general, although it'd work in this particular case if you'd put blocking gService.run() call before the end of the scope.
participants (2)
-
Alex McClung
-
Igor R