繁体   English   中英

C#串行端口从串行端口读取字节数组

[英]c# serial port read byte array from serial port

我正在尝试从串行端口读取数据并进行比较,但是我无法使其正常工作,读取的数据不是我需要获取的数据,有时它基本上是不完整的,当来自串行端口的数据到来并且数据数据相等时我想要什么到阵列以将一些数据写入串行端口

    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        var Serial1 = (SerialPort)sender;
        Serial1.DtrEnable = true;
        Serial1.RtsEnable = true;
        int bytes = Serial1.BytesToRead;
        byte[] buffer = new byte[bytes];
        Serial1.Read(buffer, 0, bytes);
        string buffer1 = System.Text.Encoding.UTF8.GetString(buffer);
        newform(buffer1);
        showinwindow(buffer);

    }

    private void showinwindow(byte[] buffer)
    {
        byte[] array1 = { 0x03, 0x2F, 0x2C };
        bool a = array1.SequenceEqual(buffer);
        if (a == true)
        {
            byte[] upisipodatak = { 0x03, 0x20, 0x23 };
            serialPort1.Write(upisipodatak, 0, upisipodatak.Length);
        }
    }

    private void newform(string buffer1)
    {
        BeginInvoke(new EventHandler(delegate
        {
                textBox1.AppendText(buffer1);
        }));
    }

我认为您的问题是,当您开始读取时,并非所有字节都可用,因此仅返回一部分。 您可能想尝试阻塞读取,方法如下:

/// <summary>
/// Attempts to read <paramref name="count"/> bytes into <paramref name="buffer"/> starting at offset <paramref name="offset"/>.
/// If any individual port read times out, a <see cref="TimeoutException"/> will be thrown.
/// </summary>

public void BlockingRead(SerialPort port, byte[] buffer, int offset, int count)
{
    while (count > 0)
    {
        // SerialPort.Read() blocks until at least one byte has been read, or SerialPort.ReadTimeout milliseconds
        // have elapsed. If a timeout occurs a TimeoutException will be thrown.
        // Because SerialPort.Read() blocks until some data is available this is not a busy loop,
        // and we do NOT need to issue any calls to Thread.Sleep().

        int bytesRead = port.Read(buffer, offset, count);
        offset += bytesRead;
        count -= bytesRead;
    }
}

请注意,这将在超时时引发异常(您可以使用SerialPort.ReadTimeout为串行端口配置超时)。

但是,请注意.Net SerialPort实现存在一些缺陷。 有关详细信息,请参见本文

特别是, SerialPort.Read()是一个阻塞调用,您通常希望避免这种情况,但是这样做将意味着您必须自己进行一些读取!

我找到了一个对我有效的解决方案,例如刚刚删除的100次中有90次

Serial1.DtrEnable = true;
Serial1.RtsEnable = true;

暂无
暂无

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

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