我正在从串口读取数据。数据来自规模。我现在正在使用 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,因为我被告知它不可靠。
任何意见/想法欢迎。这是我第一次使用串口。