Clear input data from serial port in boost::asio

余生颓废 提交于 2020-01-11 06:43:10

问题


I'm writing a C++ program for communicating with a Arduino over a serial port using boost::asio. After establishing the connection the Arduino resets itself. However the input buffer of the C++ program still contains old data sent from the Arduino. Since I have no use for this data I'd like clear the input buffer. How can I accomplish that using boost::asio?

My code currently looks like this:

#include <boost/asio.hpp>
#include <vector>
#include <iostream>

using namespace std;
using namespace boost::asio;

int main()
{
    io_service io_service;
    serial_port port(io_service, "/dev/ttyACM0");
    port.set_option(serial_port_base::baud_rate(9600));
    vector<char> buf(1);
    read(port, buffer(buf));
    cout << (int) buf[0] << endl;
    return 0;
}

The code should pause at the read command and wait for the arduino to send serial data. However there is old data causing the code to immediately continue.


回答1:


You can flush the serial buffer, which should do what you want (get rid of all pending data up to the time of the flush). Unfortunately, it seems Boost does not have a wrapper for doing this, so you have to grab the native_handle for the serial port. I based the code I'm using off this answer: https://stackoverflow.com/a/22598329/1167230



来源:https://stackoverflow.com/questions/29706262/clear-input-data-from-serial-port-in-boostasio

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