c#串口从串口读取字节数组

时间:2018-03-23 09:43:55

标签: c# arrays 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);
        }));
    }

2 个答案:

答案 0 :(得分:0)

我认为您的问题是,当您开始读取时,并非所有字节都可用,因此只返回部分数量。您可能希望尝试阻塞读取,而不是这些:

/// <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实现存在一些缺陷。 See this article for details

特别是,SerialPort.Read()是阻止通话,您通常希望避免,但这样做意味着您必须自己做一些阅读!

答案 1 :(得分:-1)

我找到了一个对我有用的解决方案,就像刚刚删除的100次中的90次一样

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