无法从串口获取数据

时间:2011-12-19 10:21:27

标签: c# serial-port

我正在使用串口com端口。 我已在程序中插入此代码。 我能够将数据发送到设备并且无法从设备读取数据。 在调试模式下,我只能获得serialport.BytesToRead = 0。 我可以知道为什么会这样吗?

   while (serialport.BytesToRead > 0)
{
      int byte_count = serialport.BytesToRead;
      byte[] buffer = new byte[byte_count];
      int read_count = serialport.Read(buffer, 0, byte_count);
      string echo = ASCIIEncoding.ASCII.GetString(buffer, 0, read_count);
      echo = System.Text.Encoding.UTF8.GetString(buffer);
      Console.WriteLine(echo);
}

1 个答案:

答案 0 :(得分:1)

何时从SerialPort读取?您发送后是否正在尝试阅读?在这种情况下,您可能会尝试在实际从端口读取任何内容之前阅读。

您应该使用DataReceived事件来读取数据。

请注意,此事件可能会在收到所有数据之前触发,因此您可能必须通过多次DataReceived调用来检索数据,直到获得所需的所有数据为止。