问题描述
我正在从串口读取数据.数据超出规模.我现在正在使用 Readline()
并且即使在我删除 DiscardInBuffer()
之后也会删除数据.
I am reading data from serial port. The data comes off the scale. I am now using Readline()
and getting data dropped even after I removed DiscardInBuffer()
.
从串口读取数据的正确方法是什么?网上的例子太少了,我觉得这就像一个没有人想出来的圣杯.
What is the proper way to read the data from the serial port? There are so few examples online that I feel it's like some holy grail that no one has figured out.
C#、WinCE 5.0、HP 瘦客户端、Compact 框架 2.0
C#, WinCE 5.0, HP thin client, 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,因为我被告知它不可靠.
One thing to note about my application is that I start the thread (weighSample) when the cursor jumps onto the textbox. The reason to this is that the weight can also be typed in manually (part of the requirements). So I don't know in advance whether a user is going to press PRINT on the balance or type the weight. In either case after the data is acquired, I exit the worker thread. Also, note that I am not using serial port event DataReceived, since I have been told it's not reliable.
这是我第一次使用串口.
This is my first experience with serial ports.
推荐答案
我从来没有在 ReadLine 工作时遇到过运气.只需在数据可用时读取本地缓冲区,然后使用单独的线程扫描数据并自行查找换行符.
I have never had luck with ReadLine working. Just do a Read into a local buffer whenever data is available and then use a separate thread to scan the data and find line breaks yourself.
这篇关于Serial Port ReadLine vs ReadExisting 或如何正确地从串口读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!