[英].NET SerialPort.Read skipps bytes
通過“port.ReadByte”讀取數據字節太慢,問題出在 SerialPort 類內部。 我將其更改為通過“port.Read”讀取更大的塊,現在沒有緩沖區溢出。
雖然我自己找到了解決方案,但寫下來對我有幫助,也許其他人也有同樣的問題,並通過谷歌找到了這個...
(我如何將其標記為已回答?)
通過設置
port.ReadBufferSize = 2000000;
我可以將問題延遲約 30 秒。 所以看起來,.Net 真的太慢了......因為我的應用程序不是那么重要,我只是將緩沖區設置為 20MB,但我仍然對原因感興趣。
我剛剛測試了一些我以前沒有想到的東西(我很慚愧):
port.ErrorReceived += (object self, SerialErrorReceivedEventArgs se_arg) => { Console.Write("| Error: {0} | ", System.Enum.GetName(se_arg.EventType.GetType(), se_arg.EventType)); };
看來我已經超支了。 .Net 實現對於 500k 來說是否太慢了,還是我這邊有錯誤?
我構建了一個非常原始的示波器(avr,它通過 uart 將 adc 數據發送到 ftdi 芯片)。 在 PC 端,我有一個顯示這些數據的 WPF 程序。
Protokoll 是:
兩個同步字節 (0xaffe) - 14 個數據字節 - 兩個同步字節 - 14 個數據字節 - ...
我使用 16 位值,所以在 14 個數據字節內有 7 個通道(lsb 在前)。
我用 hTerm 驗證了 uC 固件,它確實發送和接收了所有正確的東西。 但是,如果我嘗試使用 C# 讀取數據,有時會丟失一些字節。 oszilloscop 程序一團糟,但我創建了一個小示例應用程序,它具有相同的症狀。
我添加了兩個擴展方法 a) 從 COM 端口讀取一個字節並忽略 -1 (EOF) 和 b) 等待同步模式。
示例程序首先通過等待 (0xaffe) 同步到數據流,然后將接收到的字節與預期值進行比較。 循環運行幾次,直到彈出斷言失敗消息。 我無法通過谷歌找到任何關於丟失字節的信息,任何幫助將不勝感激。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SerialTest
{
public static class SerialPortExtensions
{
public static byte ReadByteSerial(this SerialPort port)
{
int i = 0;
do
{
i = port.ReadByte();
} while (i < 0 || i > 0xff);
return (byte)i;
}
public static void WaitForPattern_Ushort(this SerialPort port, ushort pattern)
{
byte hi = 0;
byte lo = 0;
do
{
lo = hi;
hi = port.ReadByteSerial();
} while (!(hi == (pattern >> 8) && lo == (pattern & 0x00ff)));
}
}
class Program
{
static void Main(string[] args)
{
//500000 8n1
SerialPort port = new SerialPort("COM3", 500000, Parity.None, 8, StopBits.One);
port.Open();
port.DiscardInBuffer();
port.DiscardOutBuffer();
//Sync
port.WaitForPattern_Ushort(0xaffe);
byte hi = 0;
byte lo = 0;
int val;
int n = 0;
// Start Loop, the stream is already synced
while (true)
{
//Read 7 16-bit values (=14 Bytes)
for (int i = 0; i < 7; i++)
{
lo = port.ReadByteSerial();
hi = port.ReadByteSerial();
val = ((hi << 8) | lo);
Debug.Assert(val != 0xaffe);
}
//Read two sync bytes
lo = port.ReadByteSerial();
hi = port.ReadByteSerial();
val = ((hi << 8) | lo);
Debug.Assert(val == 0xaffe);
n++;
}
}
}
}
通過“port.ReadByte”讀取數據字節太慢,問題出在 SerialPort 類內部。 我將其更改為通過“port.Read”讀取更大的塊,現在沒有緩沖區溢出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.