從Microsoft .Net 2.0版本以后,就默認提供了System.IO.Ports.SerialPort類,用戶可以非常簡單地編寫少量代碼就完成串口的信息收發程序。
1. 串口硬件信號定義
DB9 Connector 信號定義。串口測試將2、3針腳短接即可。
2、串口端口號搜索
string[] portList = System.IO.Ports.SerialPort.GetPortNames(); for (int i = 0; i < portList.Length; i++) { string name = portList[i]; comboBox.Items.Add(name); }
還有一種通過調用API的方法來獲取實現,可以獲取詳細的完整串口名稱,對於USB-to-COM虛擬串口來說特別適用。
3、串口屬性參數設置
SerialPort mySerialPort = new SerialPort("COM2");//端口 mySerialPort.BaudRate = 9600;//波特率 mySerialPort.Parity = Parity.None;//校驗位 mySerialPort.StopBits = StopBits.One;//停止位 mySerialPort.DataBits = 8;//數據位 mySerialPort.Handshake = Handshake.Non; mySerialPort.ReadTimeout = 1500; mySerialPort.DtrEnable = true;//啟用數據終端就緒信息 mySerialPort.Encoding = Encoding.UTF8; mySerialPort.ReceivedBytesThreshold = 1;//DataReceived觸發前內部輸入緩沖器的字節數 mySerialPort.DataReceived += new SerialDataReceivedEvenHandler(DataReceive_Method); mySerialPort.Open();
4、串口發送信息
- Write(Byte[], Int32, Int32) :將指定數量的字節寫入串行端口
- Write(Char[], Int32, Int32) :將指定數量的字符寫入串行端口
- Write(String) :將指定的字符串寫入串行端口
- WriteLine(String) :將指定的字符串和NewLine值寫入輸出緩沖區
// Write a string port.Write("Hello World"); // Write a set of bytes port.Write(new byte[] { 0x0A, 0xE2, 0xFF }, 0, 3); // Close the port port.Close();
5. 串口接收信息
- Read(Byte[], Int32, Int32):從SerialPort輸入緩沖區讀取一些字節,並將那些字節寫入字節數組中指定的偏移量處
- ReadByte():從SerialPort輸入緩沖區中同步讀取一個字節
- ReadChar(): 從SerialPort輸入緩沖區中同步讀取一個字符
- ReadExisting() :在編碼的基礎上,讀取SerialPort對象的流和輸入緩沖區中所有立即可用的字節
- ReadLine() :一直讀取到輸入緩沖區中的NewLine值
- ReadTo(String) :一直讀取到輸入緩沖區中的指定value的字符串
string serialReadString;
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { serialReadString = port.ReadExisting()); this.txt1.Invoke( new MethodInvoker(delegate { this.txt1.AppendText(serialReadString); })); }
6、循環接收數據
void com_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Use either the binary OR the string technique (but not both) // Buffer and process binary data while (com.BytesToRead > 0) bBuffer.Add((byte)com.ReadByte()); ProcessBuffer(bBuffer); // Buffer string data sBuffer += com.ReadExisting(); ProcessBuffer(sBuffer); } private void ProcessBuffer(string sBuffer) { // Look in the string for useful information // then remove the useful data from the buffer } private void ProcessBuffer(List<byte> bBuffer) { // Look in the byte array for useful information // then remove the useful data from the buffer }