簡體   English   中英

如何檢測 SerialPort class C# 中的串行位字節錯誤

[英]How to detect a serial bit byte error in SerialPort class C#

我正在使用 System.IO.Ports.SerialPort 從串行通信中讀取數據。 問題是我想在讀取字節數組緩沖區並寫入文件時確定哪個字節是壞的。 如果我知道哪個字節是壞的,那么我可以重新創建正確的文件,因為我知道文件的 hash。 但它看起來像 System.IO.Ports.SerialPort 只提供了一種使用 SerialPort.ParityReplace 屬性“覆蓋”錯誤字節的方法。 如果我正在讀取一百萬字節的數組,那么我不想設置一個位模式作為替換值,然后在海量數組中搜索這個位模式,因為我可能有很多匹配項。 有沒有辦法讓我在讀取字節緩沖區時確定哪個字節未通過奇偶校驗檢查? 如果不是,那么在通過串行發送文件時對我來說獲得奇偶校驗樣式錯誤檢測的更好方法是什么?

下面的代碼是我目前查看串行數據的方式,但如果它更快或提供更高的可靠性,我對其他方法持開放態度。

//... earlier code:
_serialPort.ReadBufferSize = 100000000;
//... more irrelevant code

Thread.Sleep(150000); // wait for 150 seconds for the data to come in.
byte[] HundredKBBuffer = new byte[_serialPort.ReadBufferSize]; // the byte array I'll read from
//read data then discard buffer to get new data from the transmitting machine
_serialPort.Read(HundredKBBuffer, 0, HundredKBBuffer.Length);
_serialPort.DiscardInBuffer();
Console.WriteLine("data received");
//code that reads the byte array, looks for header and trailer and writes file
findHeadAndWriteDataToFile(HundredKBBuffer);

您是否嘗試過以 stream 的形式異步讀取數據,而不是一次等待獲取整個塊? 這聽起來會讓您有更多機會進行錯誤檢查。

使用 .NET 框架讀取串口的正確方法是什么?

第一個想法是在每個字節之后進行奇偶校驗,但您可能會降低通信速度(1 個字節的數據,1 個字節的奇偶校驗)。

您也可以使用 CRC 代碼,它類似於奇偶校驗的擴展。 例如,您發送 8 個字節,第 9 個字節是 CRC。 這允許您控制指定大小的數據包的數據。 CRC function 看起來像這樣(它是 CRC-8 function,但您可以使用另一個):

private byte CRC8(byte[] Array, int length)
    {
        byte CRC = 0x00;
        int length_buffer = length;
        int length_refreshed = length;
        CRC = Array[0];
        length_refreshed--; ;
        for (; length_refreshed > 0; length_refreshed--)
        {
            CRC = (byte)(((int)CRC) ^ (int)Array[length_buffer - length_refreshed]);
        }

        return CRC;
    }

編輯在這里檢查CRC: https://en.wikipedia.org/wiki/Cyclic_redundancy_check

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM