zoukankan      html  css  js  c++  java
  • .NET 串口通信中断接收,包含0X1A(作为EOF)

    .NET串口通信中将`0X1A`当做EOF处理,.NET接收到EOF会触发一次接收中断,此时事件形参`SerialDataReceivedEventArgs`值为枚举 `Eof`,其他为`Chars`。

    参考: stackoverflow 、MSDN

    ## 测试

    .NET编程,中断方式接收,发送一串数据后等待回应,打印进中断次数;另外一端用串口助手来实现。通信用虚拟串口。

     [TestClass]
        public class EofByteSerialTest
        {
            private int _count = 0;
            private byte[] _receivedDataPacket;
            SerialPort _serialPort = new SerialPort()
            {
                PortName = "COM5",
                BaudRate = 115200,
                DataBits = 8,
                StopBits = StopBits.One,
                Parity = Parity.None
            };
            [TestMethod]
            public void TestMethod1()
            {
                _serialPort.Open();
                byte[] sendedData = { 0x01, 0x02, 0x03, 0x1a, 0x2a, 0x1a };
                _serialPort.DataReceived += ComReceive;
                _serialPort.Write(sendedData, 0, sendedData.Length);
                Thread.Sleep(10000);
                //foreach (byte b in _receivedDataPacket)
                //{
                //    Console.WriteLine(b);
                //}
                Console.WriteLine(_count);
            }
            private void ComReceive(object sender, SerialDataReceivedEventArgs e)
            {
                //if (e.EventType == SerialData.Eof)
                //{
                //    //特殊处理
                //}
                _count++;
                _receivedDataPacket = new byte[_serialPort.BytesToRead];
                _serialPort.Read(_receivedDataPacket, 0, _receivedDataPacket.Length);
                // 协议解析...
            }
        }

     串口助手数据:

    测试结果:

     

  • 相关阅读:
    evernote100个做笔记的好方法
    平衡二叉树的调整模版
    晨间日记的奇迹
    hdu 2952 Counting Sheep
    hdu 1535 Invitation Cards
    poj 3259 Wormholes(spfa)
    poj 2263 Heavy Cargo(floyd)
    poj 3268 Silver Cow Party(SPFA)
    hdu 1690 Bus System
    hdu 3631 Shortest Path(Floyd)
  • 原文地址:https://www.cnblogs.com/pangkang/p/6114293.html
Copyright © 2011-2022 走看看