我正在从串口读取数据。数据来自规模。我现在使用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,因为我被告知它不可靠。
欢迎任何评论/想法。这是我第一次使用串口。
答案 0 :(得分:11)
取决于输入数据的行尾(EOL)字符。如果您的数据是面向行的,则ReadLine是一个有效的函数,但您可能希望查看NewLine属性并确保为输入数据设置适当的。
例如,如果您的比例输出EOL换行,则设置port.NewLine = "\n";
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.newline.aspx
答案 1 :(得分:5)
我从未在ReadLine工作中幸运。只要在数据可用时读取本地缓冲区,然后使用单独的线程扫描数据并自行查找换行符。
答案 2 :(得分:1)
我想对Elias Santos发表评论,但我没有足够的声誉。使用ReadExisting方法有一些问题:
https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readexisting(v=vs.110).aspx
请注意,此方法可能会留下尾随前导字节 内部缓冲区,使BytesToRead值大于零。
之前我遇到过ReadExisting的一些问题,这是因为不需要的字节。使用Readline解决了这些问题。
答案 3 :(得分:0)
if (serialPort1->IsOpen){
if (serialPort1->BytesToRead>0){
this->textBox1->Text += serialPort1->ReadExisting();
}
}