gpt4 book ai didi

C# SerialPort 数据接收事件

转载 作者:太空宇宙 更新时间:2023-11-03 15:52:54 26 4
gpt4 key购买 nike

我正在监听串口 5 个字节的信息。轮询的完整答案需要 5 个字节。我的代码监听 serialport data_received 事件并检查 bytesToRead。有时,事件会触发并且 bytesToRead 为 0。事件不是只有在数据可用时才触发吗?

public SerialPort wheel = new SerialPort();
public void wheel_DataReceived(object sender, EventArgs e)
{
if (wheel.BytesToRead < 5)
{
wheelRetry += 1;
Log("Wheel Data Received: " + wheel.BytesToRead.ToString() +
" bytes. Need 5 bytes. Attempt #: " + wheelRetry.ToString());
}

最佳答案

您可以设置 ReceivedBytesThreshold 属性:

var port = new SerialPort();
port.Open();

//Only raise the event if 5 bytes have been received
port.ReceivedBytesThreshold = 5;

port.DataReceived += (s, e) =>
{
//Handle the data
};

请注意,您应该在打开端口后挂接事件处理程序,
这是为了防止某些平台上的已知问题,该问题会阻止事件发生
如果它在端口打开之前被连接,则会引发。

关于C# SerialPort 数据接收事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25048717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com