c#串口通信講解(一)(winform、wpf)
阿新 • • 發佈:2017-08-25
定義 cep 回調 true comm ive get exc pre
串口操作需要註意的幾點如下:
1、如果是USB轉串口;則需要安裝USB轉串口驅動,附件有此驅動。
2、串口打開狀態最好不要直接插拔串口,可能會導致中控板或者串口線燒壞。
3、使用串口調試工具CEIWEI,下一章節會貼上使用教程
簡單的串口收發通信,有以下步驟:
1、打開制定的串口、綁定串口接收事件
2、初始化串口指令
3、發送串口指令
-------打開串口代碼--------
/// <summary> /// 打開串口 /// </summary> /// <param name="strPortName">串口號</param> /// <param name="nRate">波特率</param> /// <param name="nDataBit">數據位</param> /// <param name="stopBits">停止位</param> /// /// <param name="nParity">校驗位</param> /// <returns></returns> public bool OpenSerial(string strPortName, int nRate, int nDataBit, float nStopBits, int nParity) { //這裏就是綁定串口接收回調事件,即發送一條串口命令,發送成功,則會觸發此事件進入ReciceSerialData方法,我們就進行判斷發送成功還是失敗。 serial.DataReceived += new SerialDataReceivedEventHandler(ReciveSerialData); serial.PortName = strPortName;//串口號 serial.BaudRate = nRate;//波特率 float f = nStopBits;//停止位 if (f == 0) { serial.StopBits = StopBits.None; } else if (f == 1.5) { serial.StopBits = StopBits.OnePointFive; } else if (f == 1) { serial.StopBits = StopBits.One; } else { serial.StopBits = StopBits.Two; } serial.DataBits = nDataBit;//數據位 if (nParity == 0) //校驗位 { serial.Parity = Parity.None; } else if (nParity == 1) { serial.Parity = Parity.Odd; } else if (nParity == 2) { serial.Parity = Parity.Even; } else { serial.Parity = Parity.None; } serial.ReadTimeout = 3000;//設置超時讀取時間 serial.WriteTimeout = 500;//超時寫入時間 try { if (!serial.IsOpen) { serial.Open(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); return false; } return true; }
-------使用實例--------
//定義串口對象 private SerialPort serial = new SerialPort(); //在按鈕Click事件裏調用打開串口的方法,串口COM號參數以本機具體串口號為準,COM1除外,如果只有COM1則需要安裝串口驅動,見附件 private void btnOpenSerial_Click(object sender, EventArgs e) { if (!OpenSerial("COM3", 115200, 8, 1, 0)) { //串口打開失敗 MessageBox.Show("串口打開失敗!"); } }
-------初始化串口命令、發送指令-------
註:我這個命令並不是通用的,是根據我這邊的中控板協議;發對應的命令,但是其他中控板的命令格式也是差不多的
/// <summary> /// 初始化串口命令 /// </summary> /// <param name="nStaus">操作類型</param> public void InitialSerialCommand(int nStaus) { byte[] btyData = new byte[100]; btyData[0] = 0x5A; btyData[1] = 0x55; btyData[2] = 0x00; btyData[3] = 0x00; btyData[4] = 0x02; btyData[5] = 0xD1; btyData[6] = 0x00; btyData[7] = 0x18; btyData[8] = 0x6A; btyData[9] = 0x69; //開燈 if (nStaus == 0) { btyData[6] = 0x01; } //全關 else { btyData[6] = 0x00; } //發送指令 if (serial != null) { try { SerialWrite(0, btyData); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } }
---------串口回調方法-----------
/// <summary> /// 接收數據事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ReciveSerialData(object sender, SerialDataReceivedEventArgs e) { try { if (serial.BytesToRead == 0) { return; } byte[] btyReciveData = new byte[serial.BytesToRead]; byte[] btyResoureData = new byte[btyReciveData.Length]; string strData = string.Empty; int intSp = serial.Read(btyReciveData, 0, btyReciveData.Length);//在此就可以讀取到當前緩沖區內的數據 int i = 0; string[] hex = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; for (i = 0; i < btyReciveData.Length; i++) { btyResoureData[i] = Convert.ToByte(("0x" + (hex[btyReciveData[i] / 16]).ToString() + (hex[btyReciveData[i] % 16]).ToString()), 16); } for (int a = 0; a < btyReciveData.Length; a++) { strData += btyResoureData[a].ToString("X2"); } //若串口命令發送成功,則會返回和發送指令一樣的指令,我發送的指令是(5A55000002D101186A69 );返回的也是(5A55000002D101186A69 );則可以判定串口數據交互成功。 if (strData.IndexOf("5A55000002D101186A69") >= 0) { //發送成功 } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
DEMO實例:https://files.cnblogs.com/files/henryzong/%E4%B8%B2%E5%8F%A3%E9%80%9A%E4%BF%A1DEMO.zip
串口驅動:https://files.cnblogs.com/files/henryzong/%E4%B8%B2%E5%8F%A3%E9%A9%B1%E5%8A%A8.zip
串口調試工具:https://files.cnblogs.com/files/henryzong/%E4%B8%B2%E5%8F%A3%E8%B0%83%E8%AF%95%E5%B7%A5%E5%85%B7.zip
c#串口通信講解(一)(winform、wpf)