Clear serial port receive buffer in C#(在C#中清除串口接收缓冲区)
问题描述
只想知道如何在 C# 中清除我的串口的接收缓冲区.似乎接收缓冲区中的数据只是不断累积.例如,传入数据的流向是:[Data A]、[Data B]、[Data C].我想要的数据只是[Data C].我正在考虑这样做,当我收到 [Data A] 和 [Data B] 时,我会做一个清除缓冲区.仅当收到 [Data C] 时,我才继续处理.这是在 C# 中实现的方式吗?
Just want to know how do we clear the receive buffer of my serial port in C#. Seems like the data in the receive buffer just keep accumulating. For example, the flow of incoming data is: [Data A], [Data B], [Data C]. The data I want is just [Data C]. I'm thinking of doing like, when I receive [Data A] and [Data B], I do a clear buffer. Only when [Data C] is received, I continue process. Is this the way to do it in C#?
推荐答案
如果你使用的是 System.IO.Ports.SerialPort 那么你可以使用这两种方法:
If you are using the System.IO.Ports.SerialPort then you could use the two methods:
DiscardInBuffer() 和 DiscardOutBuffer() 刷新缓冲区.
如果你是从串口读取数据:
If you are reading the data from a serial port:
private void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (!this.Open) return; // We can't receive data if the port has already been closed. This prevents IO Errors from being half way through receiving data when the port is closed.
string line = String.empty;
try
{
line = _SerialPort.ReadLine();
line = line.Trim();
//process your data if it is "DATA C", otherwise ignore
}
catch (IOException ex)
{
//process any errors
}
}
这篇关于在C#中清除串口接收缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在C#中清除串口接收缓冲区
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
