Reading from serial port with Boost Asio

回眸只為那壹抹淺笑 提交于 2019-11-29 04:36:05

This article is helpful in understanding how ASIO can be used asynchronously with serial ports:

UPDATE (2019-03):

The original article I had linked to is no longer available and is difficult to find even in Internet Archive. (Here is a snapshot.). There are now newer articles on using ASIO for serial I/O found easily by searching, but this older article is still very useful. I'm putting it in a public gist so that it doesn't get lost:

The code described in the article appears to have been copied here:

The author seems to have updated it for C++11. I believe the article was originally written by fede.tft.

OcularProgrammer

Jason,

If it is suitable for your application, I'd highly recommend implementing a callback-based asynchronous serial RX. How do I perform a nonblocking read using asio? has a great little example of how to implement asynch serial with a timeout. As you recognised, it will require a multi-threaded implementation to get the performance advantages, so you will need to put some thought where your recieved data will be buffered to make sure you aren't doing a lot of copying.

As far as the boost::streambuff stuff goes, I personally prefer just to block out some memory as a char array - char m_RXBuffer[m_RXBuffSize] and use boost::asio::buffer(m_RXBuffer, m_RXBuffSize) to pass the target buffer into async_read_some. In particular for RS232, I have always found the fact that the underlying data is a stream of bytes naturally maps a lot better onto a simple char array than any of the more complex data structures.

Good Luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!