我正在尝试使用c#串口读取数据秤到我的电脑。
在这样的putty输出中:
60KG
60KG
60KG
60KG
然后我使用下面的脚本在richtextbox中显示它:
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
if (InvokeRequired) //<-- Makes sure the function is invoked to work properly in the UI-Thread
BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); })); //<-- Function invokes itself
else
{
while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
{
String tampung = _serialPort.ReadExisting();
String tampungy = Regex.Replace(tampung, @"[^\d]", "").Trim();
richTextBox2.AppendText(tampungy + System.Environment.NewLine);
richTextBox2.ScrollToCaret();
}
}
}
但显示如下
6
0
6
0
6
0
有什么不对吗?
答案 0 :(得分:0)
看起来你正在阅读每个角色到来时的数据。为了证明这一点,你可以这样做:
var data = new byte[_serialPort.BytesToRead];
_serialPort.Read(data, 0, data.Length);
tampungy = string.Join(" ", data.Select(b => b.ToString("X2"));
richTextBox2.AppendText(tampungy + System.Environment.NewLine);
richTextBox2.ScrollToCaret();
它应该打印出每个字节读取的十六进制编码。 0D 0A
(CR LF)和0A
(LF)是换行符。 30
或39
是数字(0-9)。
您应该缓冲输入,直到读取换行符。
private StringBuilder _buffer = new StringBuilder();
private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
{
if (InvokeRequired) //<-- Makes sure the function is invoked to work properly in the UI-Thread
BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); })); //<-- Function invokes itself
else
{
while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
{
_buffer.Append(_serialPort.ReadExisting());
}
// Look for the first linebreak in the buffer
int index = Enumerable.Range(0, _buffer.Length).FirstOrDefault(i => _buffer[i] == '\n'); // 0 if not found
while (index > 0) {
// Extract and remove the first line
string tampung = _buffer.ToString(0, index);
_buffer.Remove(0, index + 1);
String tampungy = Regex.Replace(tampung, @"\D+", "");
richTextBox2.AppendText(tampungy + System.Environment.NewLine);
richTextBox2.ScrollToCaret();
// Look for the next linebreak, if any
index = Enumerable.Range(0, _buffer.Length).FirstOrDefault(i => _buffer[i] == '\n'); // 0 if not found
}
}
}