Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change serial port speed on the fly with boost::asio (or how to find out if the hardware buffer is empty)?

I'm having a peculiar problem with boost::asio and a boost::asio::serial_port device. The code is finally working pretty well with asynchronous reads and stuff, but I can't figure out how to change the speed of the serial port on the fly.

What I'm trying to do right now is just telling the device connected in my serial port to change the serial port speed to say 38400 baud, then I'm setting my computers serial port to the same speed via:

port_.set_option(boost::asio::serial_port_base::baud_rate(rate));

But what's really happening is that if I do the set_option part, the device never receives the command to change the speed. If I don't do the set_option part the device changes speed correctly. From what I gather what's happening is that the (blocking, synchronous) write puts stuff in the hardware buffer on my computer and returns, then does the set_option which discards the buffer (before it has had time to send data to the device). So I need to think of some way to check if the hardware buffer is empty and the device really has received the command to change the speed, before reconfiguring my computers serial port. I also cannot find any info on if I have to do close() and open() on the port for the speed change to take affect. I'm also wondering if close() discards the stuff in the buffer or not... I'm using a USB->serial port adapter and my platform is Ubuntu 10.10 if it makes any difference.

like image 884
Dago Avatar asked Dec 16 '10 14:12

Dago


1 Answers

Have you looked at man 3 termios? It seems tcdrain does what you need

tcdrain() waits until all output written to the object referred to by fd has been transmitted.

You can get the native descriptor from the boost::asio::serial_port::native method.

like image 128
Sam Miller Avatar answered Oct 16 '22 06:10

Sam Miller