Serial Port ReadLine vs ReadExisting或如何正确读取串口数据

我正在从串口读取数据。 数据来自规模。 我现在使用Readline()并在删除DiscardInBuffer()后删除数据。 从串口读取数据的正确方法是什么? 网上的例子很少,我觉得这就像是一些没有人想到的圣杯。

有什么帮助吗?

好像串口是一个反复无常的孩子。

C#,WinCE 5.0,HP瘦客户端,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() 

关于我的应用程序需要注意的一点是,当光标跳到文本框时,我启动线程(weighSample)。 这样做的原因是重量也可以手动输入(部分需求)。 所以我事先并不知道用户是否要在天平上按PRINT或输入重量。 在获取数据之后的任何一种情况下,我退出工作线程。 另外,请注意我没有使用串行端口事件DataReceived,因为我被告知它不可靠。

任何意见/想法欢迎。 这是我第一次使用串口。

从来没有幸运使用过ReadLine。 只要在数据可用时读取本地缓冲区,然后使用单独的线程扫描数据并自行查找换行符。

取决于输入数据的行尾(EOL)字符。 如果您的数据是面向行的,则ReadLine是一个有效的函数,但您可能需要查看NewLine属性并确保为输入数据设置了相应的属性。

例如,如果您的比例输出EOL的换行,则设置port.NewLine = "\n";

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.newline.aspx

我想对Elias Santos发表评论,但我没有足够的声誉。 使用ReadExisting方法有一些问题:

https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readexisting(v=vs.110).aspx

请注意,此方法可以在内部缓冲区中留下尾随前导字节,这会使BytesToRead值大于零。

我之前遇到过ReadExisting的一些问题,这是因为不需要的字节。 使用Readline解决了这些问题。

 if (serialPort1->IsOpen){ if (serialPort1->BytesToRead>0){ this->textBox1->Text += serialPort1->ReadExisting(); } }