首次使用C#編寫與COM口有關的程式,期間遇到了很多問題,寫下自己的經驗總結,如有錯漏,歡迎批評指正! 1、新建一個串口類( SerialPort類) 2、串口埠號搜索: 3、讀數據、顯示數據: 4、寫數據: 5、常用的埠設置和方法: 串口最基本的功能就是實現通信,簡單來說就是讀和寫,就像大家熟 ...
首次使用C#編寫與COM口有關的程式,期間遇到了很多問題,寫下自己的經驗總結,如有錯漏,歡迎批評指正!
1、新建一個串口類( SerialPort類)
1 //Create a serial port for bluetooth 2 SerialPort BluetoothConnection = new SerialPort();
2、串口埠號搜索:
string[] Ports = SerialPort.GetPortNames();
or (int i = 0; i < Ports.Length; i++)
{
string name = Ports[i];
comboBox.Items.Add(name);//顯示在消息框裡面
}
3、讀數據、顯示數據:
byte[] data = new byte[length]; BluetoothConnection.Read(data,0,length); for (int i = 0; i < length; i++) { BlueToothReceivedData += string.Format("data[{0}] = {1}\r\n", i, data[i]);//"+="表示接收數據事件發生時,觸發"+="後面的語句 }
4、寫數據:
byte[] head = new byte[8] { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };//隨便寫的一組數據,裡面的數據無意義 BluetoothConnection.Write(head, 0, head.Length);
5、常用的埠設置和方法:
BluetoothConnection.Open();//打開藍牙串口 BluetoothConnection.ReadTimeout=10000;//設置或獲取數據超時之前的毫秒數 BluetoothConnection.DataReceived;//藍牙串口接收了數據 BluetoothConnection.BaudRate;//設置串口的波特率 BluetoothConnection.BytesToRead;//藍牙所收到的緩衝區里數據的數據長度 BluetoothConnection.ReadByte();//從串口輸入緩衝區里讀一個位元組
BluetoothConnection.Close();//關閉藍牙串口
串口最基本的功能就是實現通信,簡單來說就是讀和寫,就像大家熟知的那樣,把大象裝進冰箱只需要三步:打開藍牙串口,操作和處理數據,關閉藍牙串口。
建議在手機上下載一個藍牙助手,可以清楚具體地看到數據收發的結果。
另外,如果要設置藍牙模塊的波特率、密碼等,需要在電腦上下載串口軟體。