-1

我正在尝试使用 c# 串行端口将数据称重秤读取到我的计算机上。

在这样的腻子输出中:

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

有什么不对 ?

4

1 回答 1

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
        }
    }
}
于 2017-01-17T09:27:40.127 回答