如何从串行端口获取数据

本文关键字:获取 数据 串行端口 | 更新日期: 2023-09-27 18:20:23

我有这段代码,但我不知道如何获取数据并将其放入一个变量中:

 protected override void OnStart(string[] args)
        {
            /* This WaitHandle will allow us to shutdown the thread when
               the OnStop method is called. */
            _shutdownEvent = new ManualResetEvent(false);
            /* Create the thread.  Note that it will do its work in the
               appropriately named DoWork method below. */
            _thread = new Thread(DoWork);
            /* Start the thread. */
            _thread.Start();
        }

然后在DoWork中,我有以下内容:

private void DoWork()
        {
//opening serial port 
            SerialPort objSerialPort;
            objSerialPort = new SerialPort();
            objSerialPort.PortName = "COM2";
            objSerialPort.BaudRate = 11500;
            objSerialPort.Parity = Parity.None;
            objSerialPort.DataBits = 16;
            objSerialPort.StopBits = StopBits.One;
            objSerialPort.Open();

所以,我打开了端口,但从哪里开始获取数据???如何初始化变量?所接收的消息的形式为52 45 41 44 45 52 30 31,其中41 44 45 53 30是十六进制的消息,而52 45是报头和31 CRC。

请让我知道怎么做。

谢谢。。。。

如何从串行端口获取数据

使用串行端口就像使用文件或套接字一样:

while ((bytesRead = objSerialPort.Read(buffer, 0, buffer.Length)) > 0)
{
    var checksum = buffer[bytesRead - 1];
    if (VerifyChecksum(checksum, buffer, bytesRead))  // Check the checksum
    {
        DoSomethinWithData(buffer, bytesRead);  // Do something with this bytes
    }
}
byte[] buffer = new byte[1];
String message = "";
While (true)
{
  if(objSerialPort.Read(buffer,0,1)>0)
  {
  message+= System.Text.Encoding.UTF8.GetChars(buffer).ToString();
  //Or you could call another function here that will DoSomething with each byte coming in!
  }
}

应该这么做!