繁体   English   中英

如何从串口获取数据?

[英]How to get data from serial port?

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

 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!
  }

}

应该做的把戏!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM