在C#中使用COM端口而不是获取所有已发送的数据

时间:2013-03-04 21:27:09

标签: c# .net-3.5 serial-port

只是为了解释,我有一个开发板,按命令,射出4个字符(字节)。我用来调试它的终端程序(RealTerm)可以看到所有4个字节。我现在已经开始编写桌面软件,我的程序只关注发送的4个字节中的1个。为了澄清,我不知道4个字节中的哪一个(第一个,最后一个,中间两个),但我可以找出它是否真的有必要。

首先,我认为SerialPort.DataReceived事件将针对收到的每个字节触发。事实并非如此,我不知道是什么原因引发它,但它不是接收一个单一的字节。

所以我尝试在SerialPort.BytesToRead上循环,但这也只获取第一个字节,即使它识别出有3个字节要读(为什么不是4?)

对我来说,在它到达端口的确切时间接收这些数据并不是必不可少的,但显然我想要丢失3/4的数据。然而,它不会总是4个字节,这正是它现在正在做的事情。我只想获得准备好读取的所有字节。

事件处理程序:

private void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            while (comPort.BytesToRead > 0)
            {
                RxString = comPort.ReadExisting();
                RxByte = comPort.ReadByte(); 
                byte[] myByte = new byte[6];

                for (int i = 0; i < 6; i++)
                {
                    myByte[i] = 0000000;
                }

                comPort.Read(myByte, 0, comPort.BytesToRead);
                for (int i=0;i<6;i++)
                {
                    if (myByte[i] != null)
                    {
                        thisBytes.Add(myByte[i]);
                    }
                }
                RxString = RxByte + "";
                try
                {
                    this.Invoke(new EventHandler(dealWithByte));
                }
                catch
                {

                }
            }
        }


private void dealWithByte(object sender, EventArgs e)
        {
            foreach (byte item in thisBytes)
            {
                RxByte = Convert.ToInt16(item);
                string binary = Convert.ToString(RxByte, 2).PadLeft(8, '0');
                //processTime(binary);
            }
      }

1 个答案:

答案 0 :(得分:0)

我不是C#人,但代码非常简单,伪代码

    numBytes As Int = SerialPort1.BytesToRead 'get # of bytes available
    buf(numBytes - 1) As Byte 'allocate a buffer
    br As Int = SerialPort1.Read(buf, 0, numBytes) 'read the bytes
    If br <> numBytes {
        Resize(buf, br) 'resize the buffer
    }
此时

将字节存储到列表中。然后可以为消息处理该列表。