Reading from serial port with Boost Asio

后端 未结 2 791
时光取名叫无心
时光取名叫无心 2020-12-16 21:42

I\'m want to check for incoming data packages on the serial port, using boost.asio. Each data packet will start with a header that is one byte long, and will sp

2条回答
  •  旧巷少年郎
    2020-12-16 22:18

    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!

提交回复
热议问题