【问题标题】:Reading bytes from the serial port从串口读取字节
【发布时间】:2015-12-30 21:33:45
【问题描述】:

我正在构建一个应用程序,我需要从串行设备读取 15 个字节。 (ScaleXtric c7042 powerbase)字节需要按正确的顺序排列,最后一个是crc。

在后台工作人员中使用此代码,我得到字节:

byte[] data = new byte[_APB.ReadBufferSize];
_APB.Read(data, 0, data.Length);

问题是我没有首先获取第一个字节,它就像它在缓冲区中存储了一些字节,所以下次触发 DataRecieved 事件时,我从上一条消息中获取最后 x 个字节,并且只有新的 15-x 字节。我将字节写入一个文本框,而且它到处都是,所以某些地方丢失了一些字节。

我尝试在每次读取后清除缓冲区,但没有成功。

_APB = new SerialPort(comboBoxCommAPB.SelectedItem.ToString());
_APB.BaudRate = 19200;
_APB.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandlerDataFromAPB);
_APB.Open();
_APB.DiscardInBuffer();

希望有人能帮帮我

【问题讨论】:

  • 您只能获得接收缓冲区中当前可用的字节数,通常只有 1 或 2 个。计算它们是否全部由您决定。 Like this.

标签: c# winforms serial-port


【解决方案1】:

使用此方法从串口读取固定数量的字节,对于您的情况toread = 15;

 public byte[] ReadFromSerialPort(SerialPort serialPort, int toRead)
 {
     byte[] buffer = new byte[toRead];
     int offset = 0;
     int read;

    while (toRead > 0 && (read = serialPort.Read(buffer, offset, toRead)) > 0)
    {
        offset += read;
        toRead -= read;
    }
    if (toRead > 0) throw new EndOfStreamException();

    return buffer;
}

【讨论】:

    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多