簡體   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