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();//关闭蓝牙串口

串口最基本的功能就是实现通信,简单来说就是读和写,就像大家熟知的那样,把大象装进冰箱只需要三步:打开蓝牙串口,操作和处理数据,关闭蓝牙串口。

建议在手机上下载一个蓝牙助手,可以清楚具体地看到数据收发的结果。

另外,如果要设置蓝牙模块的波特率、密码等,需要在电脑上下载串口软件。

posted @ 2019-07-19 17:11  #DIDIDA#  阅读(3358)  评论(2编辑  收藏  举报