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

本文介绍使用C#进行蓝牙串口通信的方法,包括串口类创建、端口搜索、数据读写等关键步骤,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文: 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, 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 on 2019-07-20 08:47 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/11216549.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值