先看最終的效果圖:
主要實作功能是将序列槽發送過來的資料按波形顯示
注:本例是以序列槽調試助手和虛拟序列槽VSPD軟體模拟序列槽發送資料的,詳細說明見下文
說明:
serialPort的ReadByte()方法用于從System.IO.Ports.SerialPort輸入緩沖區中同步讀取一個位元組。
chart控件的spline為曲線圖,以光滑的曲線連接配接各點。
幾個代碼塊說明:
(1)
private void SearchAndAddSerialToCombobox(SerialPort Myport, ComboBox Mybox)
{
string Buffer;
Mybox.Items.Clear();
for (int i = 1; i < 20; i++)
{
try
{
Buffer = "COM" + i.ToString();
Myport.PortName = Buffer;
Myport.Open();
Mybox.Items.Add(Buffer);
Myport.Close();
}
catch
{ }
}
}
這段代碼功能是尋找可用的序列槽并添加到comboBox下拉選項中。原理是逐個測試序列槽是否可用,一般來說電腦1-20就足夠了,如果超過20個,可修改。
(2)
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] data_receive = new byte[3];
data_receive[0] = (byte)serialPort1.ReadByte();
data_receive[1] = (byte)serialPort1.ReadByte();
data_receive[2] = (byte)serialPort1.ReadByte();
textBox1.AppendText(data_receive[0].ToString()+" ");
textBox1.AppendText(data_receive[1].ToString());
textBox1.AppendText(data_receive[2].ToString()+"\r\n");
series.Points.AddY(data_receive[0]);
/* int data_receive = serialPort1.ReadByte();
textBox1.AppendText(data_receive.ToString()+" ");
series.Points.AddY(data_receive);*/
}
這段代碼是将序列槽資料顯示在chart表格中,這裡的代碼需要根據自己實際傳送的資料加以修改,不難,textbox控件就可以顯示,若用源碼資源(文章末尾)中帶的序列槽調試助手當做發送則不用修改。
我所用的序列槽調試助手每次發送過來的單位元組都會自動在末尾加換行“\r\n”,是以我用讀三次顯示第一個方式記錄資料,序列槽調試助手發送時記得勾選hex發送,每次發送一個位元組。
源碼下載下傳:http://download.csdn.net/detail/u012342996/9513760
(注:該資源中有序列槽調試助手,但無VSPD,VSPD自行百度下載下傳即可)
serialPort的ReadByte()方法用于從System.IO.Ports.SerialPort輸入緩沖區中同步讀取一個位元組。