C#串口通訊

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
           // serialPort1.PortName = "COM1";
            
            serialPort1.WriteLine("@00WD7100001158*\r");
            
 
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //數據接收完整性
            //這裏不知道是用延時好,還是循環讀取緩衝區好,待驗證……
            //Thread.Sleep(50);
            string data = string.Empty;
            while (serialPort1.BytesToRead > 0)
            {
                data += serialPort1.ReadExisting();  //數據讀取,直到讀完緩衝區數據
            }
 
            //更新界面內容時UI不會卡
            this.Invoke((EventHandler) delegate
            {
                //定義一個textBox控件用於接收消息並顯示
                textBox1.AppendText(data + Environment.NewLine);
            });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            serialPort1.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            serialPort1.Open();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章