如何从串口获取数据?

贝斯琳达N.

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章