如何从串行端口读取特定字符串?

时间:2014-01-08 22:12:53

标签: c# serial-port

我正在串口谈论智能马达,我正试图寻找从马达回来的特定字符串“@ Positon”。当我看到我想要启用播放按钮时(btnPlay.Enabled = true;)。

我已经尝试过各种方式,但似乎无法适应以下代码。我可以在下面的代码中放置什么,我可以测试传入的数据,然后触发启用?

以下代码有效 - 我只是不知道在哪里以及如何阅读特定信息。

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
  // If the com port has been closed, do nothing
  if (!comport.IsOpen) return;

  // Determain which mode (string or binary) the user is in
  if (CurrentDataMode == DataMode.Text)
  {
    // Read all the data waiting in the buffer
    string data = comport.ReadExisting();

    // Display the text to the user in the terminal
    Log(LogMsgType.Incoming, data);
  }
  else
  {
    // Obtain the number of bytes waiting in the port's buffer
    int bytes = comport.BytesToRead;

    // Create a byte array buffer to hold the incoming data
    byte[] buffer = new byte[bytes];

    // Read the data from the port and store it in our buffer
    comport.Read(buffer, 0, bytes);

    // Show the user the incoming data in hex format
    Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));
  }
}

0 个答案:

没有答案