Пример #1
0
        private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(100); //延时 100ms 等待接收完数据
                                                //this.Invoke 就是跨线程访问 ui 的方法,也是本文的范例
            // invoke匿名委托
            this.Invoke((EventHandler) delegate
            {
                if (isHex == false)
                {
                    if (sp.BytesToRead > 0)
                    {
                        tbxRecvData.Text  = "";
                        tbxRecvData.Text += sp.ReadLine();
                    }
                }
                else
                {
                    Byte[] ReceivedData = new Byte[sp.BytesToRead]; //创建接收字节数组
                    sp.Read(ReceivedData, 0, ReceivedData.Length);  //读取所接收到的数据

                    UartProtocol up = new UartProtocol();
                    up.revNewData(ReceivedData);
                    if (up.isFinished())
                    {
                        byte[] temp         = up.packageData();
                        String RecvDataText = null;
                        for (int i = 0; i < temp.Length; i++)
                        {
                            RecvDataText += ("0x" + temp[i].ToString("X2") + " ");// X 十六进制 2每次两位数
                        }
                        tbxRecvData.Text  = "";
                        tbxRecvData.Text += RecvDataText;
                    }
                }
                sp.DiscardInBuffer();//丢弃接收缓冲区数据
            });
        }
Пример #2
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            // 模拟数据包
        #if false
            byte[]       a1 = { 0xA7, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x01, 0x01 };
            byte[]       a2 = { 0x01, 0x02, 0x03, 0x04 };
            byte[]       a3 = { 0xA7, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x01, 0x01 };
            byte[]       a4 = { 0x00, 0x00, 0x05, 0x01, 0x01 };
            UartProtocol up = new UartProtocol();

            byte[] b = null;

            up.revNewData(a1);

            while (!up.isFinished())
            {
                up.revNewData(a2);
            }
            b = up.packageData();
        #endif
        }