我正在使用 .Net Framework 4,在 C# 中创建串口 GUI 应用程序。在某些情况下,SerialPort 对象(port)无法接收所有数据(我将其与混合信号示波器进行比较)。
例如,如果连接的设备发送:
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09
我只能接收到:
0x00 0x01 0x02 0x03 0x04 0x08 0x09
我尝试了不同的代码,但仍然存在相同的问题。
例如,如果连接的设备发送:
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09
我只能接收到:
0x00 0x01 0x02 0x03 0x04 0x08 0x09
我尝试了不同的代码,但仍然存在相同的问题。
Use the data received event to fill a buffer:
private void dataReceived(object sender, SerialDataReceivedEventArgs e) { while (port.BytesToRead > 0){ byte[] newBytes = new byte[port.BytesToRead]; int LengthRead = port.Read(newBytes, 0, newBytes.Length); Array.Resize(ref newBytes, LengthRead); System.Buffer.BlockCopy(newBytes, 0, buffer, positionInBuffer, newBytes.Length); positionInBuffer += newBytes.Length; } }
Looping for an expected number of bytes, in this case causing the TimeoutException:
while (port.BytesToRead < expectedSize) { System.Threading.Thread.Sleep(10); waitingLoop++; if (waitingLoop > TimeOut) // wait for a 1s timeout throw new TimeoutException(); } newBytes = new byte[expectedSize]; LengthRead = port.Read(newBytes, 0, newBytes.Length); if (LengthRead != newBytes.Length) throw new TimeoutException(); // or any exception, doesn't matter...
我尝试改变ReadBufferSize的大小,超时信息等,但都没有起作用。有什么想法吗?