[英]Serial Port ReadLine vs ReadExisting or how to read the data from serial port properly
我正在从串口读取数据。 数据超出了规模。 我现在正在使用Readline()
并且即使在删除DiscardInBuffer()
之后也会丢失数据。
从串口读取数据的正确方法是什么? 网上的例子太少了,我觉得这就像是无人问津的圣杯。
C#,WinCE 5.0,惠普瘦客户机,Compact framework 2.0
private void WeighSample()
{
this._processingDone = false;
this._workerThread = new Thread(CaptureWeight);
this._workerThread.IsBackground = true;
this._workerThread.Start();
} //end of WeighSample()
private void CaptureWeight()
{
globalCounter++;
string value = "";
while (!this._processingDone)
{
try
{
value = this._sp.ReadLine();
if (value != "")
{
if (value == "ES")
{
_sp.DiscardInBuffer();
value = "";
}
else
{
this.Invoke(this.OnDataAcquiredEvent, new object[] { value });
}
}
}
catch (TimeoutException)
{
//catch it but do nothing
}
catch
{
//reset the port here?
MessageBox.Show("some other than timeout exception thrown while reading serial port");
}
}
} //end of CaptureWeight()
关于我的应用程序需要注意的一件事是,当 cursor 跳转到文本框时,我启动了线程 (weighSample)。 这样做的原因是重量也可以手动输入(部分要求)。 所以我事先不知道用户是要在天平上按 PRINT 还是输入重量。 无论哪种情况,在获取数据后,我都会退出工作线程。 另外,请注意我没有使用串行端口事件 DataReceived,因为有人告诉我它不可靠。
这是我第一次使用串口。
取决于输入数据的行尾 (EOL) 字符。 如果您的数据是面向行的,那么 ReadLine 是一个有效的 function 可以使用,但您可能需要查看 NewLine 属性并确保它已针对您的输入数据进行了适当的设置。
例如,如果您的电子秤为 EOL 输出换行符,则设置port.NewLine = "\n";
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.newline.aspx
我从来没有幸运地使用 ReadLine 工作。 只需在数据可用时读入本地缓冲区,然后使用单独的线程扫描数据并自己查找换行符。
if (serialPort1->IsOpen){
if (serialPort1->BytesToRead>0){
this->textBox1->Text += serialPort1->ReadExisting();
}
}
我正在添加一个答案来回应 Elias Santos。 使用 ReadExisting 方法有一些问题:
https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readexisting(v=vs.110).aspx
请注意,此方法可能会在内部缓冲区中留下尾随的前导字节,这使得 BytesToRead 值大于零。
我之前遇到过 ReadExisting 的一些问题,这是因为不需要的字节。 使用 Readline 解决了这些问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.