SerialPort BytesToRead返回的值比预期的高

时间:2019-09-19 11:13:23

标签: c# serial-port

我有一个微控制器(vcom),它每毫秒发送140个字节,因此我完全知道在ms,s等之后需要的数据量。在首次在DataReceivedHandler中调用调试SerialPort.BytesToRead时,它显示的值大于4000。我还希望我的数据以0xAA,0x55​​开头,因为这些是微控制器发送的第一个字节,但事实证明,这并不总是收到的。打开端口后,我丢弃了inbuffer。

与上述方法无关,我还尝试运行设置为1 ms的计时器,并在计时器内部调用comport.BytesToRead,结果相同。

您对我有什么解释吗?

public void SetComConnectParam(string portName) 
    {
        if (m_serialPort.IsOpen == false)
        {
            m_serialPort.PortName = portName;
            m_serialPort.BaudRate = 1408000;
            m_serialPort.Parity = Parity.None;
            m_serialPort.DataBits = 8;
            m_serialPort.StopBits = StopBits.One;               
            m_serialPort.ReceivedBytesThreshold = 1; //default = 1
        }
    }

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        //if (e.EventType == SerialData.Eof){return;} 
        SerialPort comport = sender as SerialPort;
        if (comport == null || comport.BytesToRead == 0 || !comport.IsOpen) { return; }
        int dataLength = comport.BytesToRead;
        byte[] buffer = new byte[dataLength];
        int nbrDataRead = comport.Read(buffer, 0, dataLength);
        if (nbrDataRead == 0) { return; }

        // add new items to the queue
        incomingdataQueue.Enqueue(buffer.Take(nbrDataRead).ToList());
    }
private bool ComOpen()
    {
        // Closing serial port if it is open
        if (m_serialPort != null && m_serialPort.IsOpen)
        {
            m_serialPort.Close();
            System.Threading.Thread.Sleep(1000);
        }

        if (false == m_serialPort.IsOpen)
        {
            try
            {
                m_serialPort.Open();
                m_serialPort.DiscardInBuffer();
            }
            catch { return false; }
        }
        return true;
    }

0 个答案:

没有答案