FTDI VCP如何读取无尽的数据流C#

时间:2018-11-28 18:21:55

标签: c# ftdi

我有微控制器以高波特率发送数据包。我需要阅读和分析这些数据以构建图。我使用了SerialPort类和Thread。有时会出现线程冻结并丢失一些数据包的问题。

打开端口功能:

 private void OpenPortButton_Click(object sender, RoutedEventArgs e)
    {
        _port.Parity = (Parity)ParityChooserBox.SelectedItem;
        _port.PortName = (string)PortChooserBox.SelectedItem;
        _port.BaudRate = (int)BaudRateChooserBox.SelectedItem;
        _port.DataBits = (int)DataBitsChooserBox.SelectedItem;
        _port.StopBits = (StopBits)StopBitsChooserBox.SelectedItem;
        try
        {
            _port.Open();
        }
        finally
        {
        }

        _readThread = new Thread(ReadData);
        _readThread.Start();
    }

读取功能:

private void ReadData()
    {
        var Data = new List<int>();
        while (true)
        {
            if (_stopThread)
                break;
            Data.Add(_port.ReadByte());
            if (_readPacket && _currentPacketSize != 0)
            {
                _currentPacketSize--;
            }
            else if (_readPacket && _currentPacketSize == 0)
            {
                var delegateAnalyza = new AnalyzaDel(Analyze);
                Dispatcher.Invoke(delegateAnalyza, Data);
                _readPacket = false;
                Data = new List<int>();
            }
            else
            if (_readSize)
            {
                _readPacket = true;
                _currentPacketSize = Data[Data.Count - 1];
                _readSize = false;
            }
            else
            if (Data.Count >= 3 && Data[Data.Count - 1] == Data[Data.Count - 2] && Data[Data.Count - 3] == Data[Data.Count - 1] &&
                Data[Data.Count - 1] == 255)
            {
                _readSize = true;
            }
        }
    }

数据包以3个0xFF字节开头。

0 个答案:

没有答案