C#:藍牙串口讀數據和寫數據


  首次使用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();//關閉藍牙串口

串口最基本的功能就是實現通信,簡單來說就是讀和寫,就像大家熟知的那樣,把大象裝進冰箱只需要三步:打開藍牙串口,操作和處理數據,關閉藍牙串口。

建議在手機上下載一個藍牙助手,可以清楚具體地看到數據收發的結果。

另外,如果要設置藍牙模塊的波特率、密碼等,需要在電腦上下載串口軟件。


免責聲明!

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



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