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

C#:蓝牙串口读数据和写数据,第1张

概述原文: C#:蓝牙串口读数据和写数据   首次使用C#编写与COM口有关的程序,期间遇到了很多问题,写下自己的经验总结,如有错漏,欢迎批评指正! 1、新建一个串口类(nbsp;SerialPort类) 1 //Create a serial port for bluetooth2 SerialPort BluetoothConnection = new SerialPort(); 2、串口端口 原文: C#:蓝牙串口读数据和写数据

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

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

1 //Create a serial port for bluetooth2 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();//关闭蓝牙串口

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

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

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

总结

以上是内存溢出为你收集整理的C#:蓝牙串口读数据和写数据全部内容,希望文章能够帮你解决C#:蓝牙串口读数据和写数据所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1232562.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存