微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#:蓝牙串口读数据和写数据

原文: C#:蓝牙串口读数据和写数据

  首次使用C#编写与COM口有关的程序,期间遇到了很多问题,写下自己的经验总结,如有错漏,欢迎批评指正!

1、新建一个串口类(nbsp;SerialPort类)

1 //Create a serial port for bluetooth
2 SerialPort BluetoothConnection = new SerialPort();

2、串口端口号搜索

string[] Ports = SerialPort.GetPortNames();
or (int i = 0; i lt; Ports.Length; i++)
{
nbsp;nbsp;nbsp; string name = Ports[i];
nbsp;nbsp;nbsp; comboBox.Items.Add(name);//显示在消息框里面
}

3、读数据、显示数据:

byte[] data = new byte[length];
            BluetoothConnection.Read(data,0,length);
            for (int i = 0; i lt; length; i++)
            {
                BluetoothReceivedData += string.Format("data[{0}] = {1}\r\n",i,data[i]);//"+="表示接收数据事件发生时,触发"+="后面的语句
            }

4、写数据:

byte[] head = new byte[8] { 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();//关闭蓝牙串口

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐