简体   繁体   English

我可以设置SerialPort 的DataReceived 事件发生的周期吗?

[英]Can I set the cycle that DataReceived event occurs from SerialPort?

I have a program that reads and writes a hexadecimal byte[] from SerialPort .我有一个程序可以从SerialPort读取和写入十六进制 byte[] 。

My program only use 5 bytes(five hexadecimal) in one communication.我的程序在一次通信中只使用 5 个字节(五个十六进制)。

The problem is that the DataReceived occurence cycle is random.问题是 DataReceived 的出现周期是随机的。 So, sometimes it reads 5 bytes, sometimes it reads 4 bits.所以,有时它读取 5 个字节,有时它读取 4 位。

在此处输入图像描述

I always want DataReceived to read 5 bytes.我总是希望 DataReceived 读取 5 个字节。 Is it possible?是否可以?

Below code is the logic of program that I wrote.下面的代码是我写的程序的逻辑。

serialPort.Write(sendData, 0, sendData.Length);
serialPort.DataReceived += (sender, e) =>
{
    var receiveSize = serialPort.BytesToRead;
    var buffer = new byte[receiveSize];

    serialPort.Read(buffer, 0, buffer.Length);
    this.Invoke(() =>
    {
        readRichTextBox.AppendText($"{string.Join(" ", Encoding.UTF8.GetString(buffer))}\n");
    });
};

I solved it after creating a empty List<byte> .我在创建一个空的List<byte>后解决了它。 Is there a better way?有没有更好的办法?

private List<byte> bytes = new List<byte>();
serialPort.DataReceived += (sender, e) =>
{
    var receiveSize = serialPort.BytesToRead;
    var buffer = new byte[receiveSize];

    serialPort.Read(buffer, 0, buffer.Length);

    this.Invoke(() =>
    {
        foreach (var b in buffer)
        {
            bytes.Add(b);
        }

        if (bytes.Count == 10)
        {
            readRichTextBox.AppendText($"{string.Join(" ", Encoding.UTF8.GetString(bytes.ToArray()))}\n");
            bytes.Clear();
        }
    });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM