asio中从串行端口清除输入数据

asio中从串行端口清除输入数据

本文介绍了在boost :: asio中从串行端口清除输入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个C ++程序,用于使用boost :: asio通过串行端口与Arduino通信.建立连接后,Arduino会自行重置.但是,C ++程序的输入缓冲区仍然包含从Arduino发送的旧数据.由于我没有必要使用此数据,因此我想清除输入缓冲区.如何使用boost :: asio完成该操作?

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;
}

代码应在读取命令处暂停,并等待arduino发送串行数据.但是,有一些旧数据导致该代码立即继续执行.

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.

推荐答案

您可以刷新串行缓冲区,该缓冲区应执行您想要的操作(清除刷新之前的所有未决数据).不幸的是,Boost似乎没有用于执行此操作的包装程序,因此您必须获取native_handle作为串行端口.我根据这个答案使用了代码: https://stackoverflow.com/a/22598329/1167230

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

这篇关于在boost :: asio中从串行端口清除输入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:15