清除 boost::asio 中串口的输入数据 [英] Clear input data from serial port in boost::asio

查看:36
本文介绍了清除 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 中串口的输入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆