我正在从串口读取数据。数据超出了规模。我现在正在使用 Readline()
,即使在我删除 DiscardInBuffer()
之后数据也会丢失。
从串口读取数据的正确方法是什么?网上的例子太少了,我觉得这就像是无人问津的 chalice 。
C#、WinCE 5.0、HP 瘦客户机、Compact 框架 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,因为有人告诉我它不可靠。
这是我第一次使用串口。
最佳答案
取决于输入数据的行尾 (EOL) 字符。如果您的数据是面向行的,那么 ReadLine 是一个可以使用的有效函数,但您可能需要查看 NewLine 属性并确保它针对您的输入数据进行了适当的设置。
例如,如果您的秤为 EOL 输出换行符,则设置 port.NewLine = "\n";
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.newline.aspx
关于c# - Serial Port ReadLine vs ReadExisting 或如何从串口正确读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/636758/