C# SerialPort如何讀取串口數據庫並顯示在TextBox上


C#SerialPort如何讀取串口數據並顯示在TextBox上

  SerialPort中串口數據的讀取與寫入有較大的不同。由於串口不知道數據何時到達,因此有兩種方法可以實現串口數據的讀取。一、線程實時讀串口;二、事件觸發方式實現。

  由於線程實時讀串口的效率不是十分高效,因此比較好的方法是事件觸發的方式。在SerialPort類中有DataReceived事件,當串口的讀緩存有數據到達時則觸發DataReceived事件,其中SerialPort.ReceivedBytesThreshold屬性決定了當串口讀緩存中數據多少個時才觸發DataReceived事件,默認為1。

  另外,SerialPort.DataReceived事件運行比較特殊,其運行在輔線程,不能與主線程中的顯示數據控件直接進行數據傳輸,必須用間接的方式實現。如下:

  SerialPort spSend;//spSend,spReceive用虛擬串口連接,它們之間可以相互傳輸數據。spSend發送數據

  SerialPort spReceive; //spReceive接受數據

  TextBox txtSend; //發送區

  TextBox txtReceive; //接受區

  Button btnSend; //數據發送按鈕

  delegate void UpdateTextEventHandler(string text);//委托,此為重點

  UpdateTextEventHandler updateText;

  public void InitClient() //窗體控件已經初始化

  {

  updateText = new UpdateTextEventHandler(UpdateTextBox);//實例化委托對象

  spSend.Open(); //SerialPort對象在程序結束前必須關閉,在此說明

  spReceive.DataReceived += newPorts.SerialDataReceivedEventHandler(spReceive_DataReceived);

  spReceive.Open();

  }

  public void btnSend_Click(object sender,EventArgse)

  {

  spSend.WriteLine(txtSend.Text);

  }

  public void spReceive_DataReceived(objectsender,Ports.SerialDataReceivedEventArgs e)

  {

  //byte[] readBuffer = newbyte[spReceive.ReadBufferSize];

  //spReceive.Read(readBuffer, 0,readBuffer.Length);

  //this.Invoke(updateText, new string[] {Encoding.Unicode.GetString(readBuffer) });

  string readString = spReceive.ReadExisting();

  this.Invoke(updateText,new string[]{readString});

  }

  private void UpdateTextBox(string text)

  {

  txtReceive.Text = text;

  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM