SerialPort 数据丢失 - C#

SerialPort data loss - C#(SerialPort 数据丢失 - C#)

本文介绍了SerialPort 数据丢失 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 SerialPort 应用程序,其中一个非常简单的部分就是给我带来问题.我只是想从端口读取恒定的数据流并将其写入二进制文件.问题似乎是速度:我的代码在我的 9600 波特测试设备上运行良好,但是当转移到115200bps 实时设备,我似乎正在丢失数据.发生的事情是在一段可变的时间之后,我错过了 1 个字节,这会丢弃其余数据.我尝试了一些方法:

I'm working on a SerialPort app and one very simple part of it is giving me issues. I simply want to read a constant stream of data from the port and write it out to a binary file as it comes in. The problem seems to be speed: my code has worked fine on my 9600 baud test device, but when carried over to the 115200bps live device, I seem to be losing data. What happens is after a variable period of time, I miss 1 byte which throws off the rest of the data. I've tried a few things:

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    bwLogger.Write((byte)serialPort1.ReadByte());
}

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    byte[] inc = new byte[serialPort1.BytesToRead];
    serialPort1.Read(inc, 0, inc.Length);

    bwLogger.Write(inc);
}

还有一些变化.我无法使用 ReadLine(),因为我正在处理恒定的数据流(对吗?).我试过摆弄缓冲区大小(serialPort1.ReadBufferSize 和硬件 FIFO 缓冲区).理想情况下,出于可用性目的,我会在软件方面处理此问题,而不是让用户必须更改 Windows 驱动程序设置.

and a few variations. I can't use ReadLine() as I am working with a constant stream of data (right?). I've tried fiddling with the buffer size (both serialPort1.ReadBufferSize and the hardware FIFO buffer). Ideally, for usability purposes, I'd handle this on the software side and not make the user have to change Windows driver settings.

有什么想法吗?

推荐答案

您可以尝试使用 SerialPort 对象的 Handshake 属性启用握手.

You might try enabling handshaking, using the Handshake property of the SerialPort object.

您必须在发送者或接收者上都设置它.但是:如果您溢出接收器的 UART 缓冲区(非常小,16 字节 IIRC),可能没有其他方法.如果您无法在发送方上启用握手,您可能必须保持在 9600 或以下.

You'll have to set it on both the sender or receiver. however: if you're overflowing the receiver's UART's buffer (very small, 16 bytes IIRC), there's probably no other way. If you can't enable handshaking on the sender, you'll probably have to stay at 9600 or below.

这篇关于SerialPort 数据丢失 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:SerialPort 数据丢失 - C#

基础教程推荐