C#串口编程

串口设置

            sp = new SerialPort(comboBox1.SelectedItem.ToString(), int.Parse(comboBox2.SelectedItem.ToString()), parity,
                int.Parse(comboBox4.SelectedItem.ToString()), stopBits);
            sp.ReceivedBytesThreshold = 16;
            sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
            sp.Open();

串口数据接收事件

        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)

        {

            try

            {

                if (isClosing)

                {

                    return;

                }

                if (!isReading)

                {

                    sp.ReceivedBytesThreshold = 10000;

                    if (watch == null)

                    {

                        watch = Stopwatch.StartNew();

                        watch.Start();

                        lastTimeLeft = TimeSpan.Zero;

                    }

                    else

                    {

                        if (sp.BytesToRead > 1024)

                            sp.DiscardInBuffer();

                        else

                        {

                            isReading = true;

                            while (sp.BytesToRead >= 16)

                            {

                                if (sp.ReadByte() == 0xAA && sp.ReadByte() == 0x55)

                                {

                                    sp.Read(dataReceived, 0, dataReceived.Length);

                                    allData.AddRange(dataReceived);

                                }

                            }

                            isReading = false;

                        }

                    }



                    sp.ReceivedBytesThreshold = 16;

                }

            }

            catch

            {

                MessageBox.Show("端口接受数据有错误,请重新打开端口!");

            }

        }

串口数据解析

            while (allData.Count >= 14)
            {
                a = (Int16)(allData[1] | allData[2] << 8);
                if (MaxOfRound < Math.Abs(a))
                {
                    MaxOfRound = a;
                }
                aY = (Int16)(allData[3] | allData[4] << 8);
                if (MaxOfRoundY < Math.Abs(aY))
                {
                    MaxOfRoundY = aY;
                }
                allData.RemoveRange(0, 14);
            }

 

你可能感兴趣的:(C#)