zoukankan      html  css  js  c++  java
  • 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);
                }

  • 相关阅读:
    dedeCMS自定义dede标签
    phpstrom配置Xdebug
    ElasticSearch安装 --- windows版
    MySQL语句优化
    PHP高并发商城秒杀
    【java_需阅读】Java中static关键字用法总结
    【java】public,private和protected
    PICT测试工具的安装及使用
    【android】Android am命令使用
    【python】获取指定网页上的所有超级链接
  • 原文地址:https://www.cnblogs.com/yshic/p/3156695.html
Copyright © 2011-2022 走看看