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

本文记录了使用C#进行蓝牙串口通信的步骤,包括创建SerialPort对象,搜索串口端口号,读取和显示数据,以及写入数据。还提到了常用端口设置和方法,以及通过手机蓝牙助手进行数据验证的建议。
摘要由CSDN通过智能技术生成

  首次使用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
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在C#中从蓝牙设备获取数据,你需要使用.NET Framework提供的Bluetooth API。以下是一个简单的代码示例: ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO.Ports; using InTheHand.Net.Sockets; using InTheHand.Net.Bluetooth; namespace BluetoothDemo { class Program { static void Main(string[] args) { // 获取本机蓝牙设备列表 BluetoothClient client = new BluetoothClient(); BluetoothDeviceInfo[] devices = client.DiscoverDevices(); // 选择要连接的设备 BluetoothDeviceInfo device = null; foreach (BluetoothDeviceInfo d in devices) { if (d.DeviceName == "MyDeviceName") { device = d; break; } } if (device != null) { // 连接设备 BluetoothClient client2 = new BluetoothClient(); BluetoothEndPoint ep = new BluetoothEndPoint(device.DeviceAddress, BluetoothService.SerialPort); BluetoothClient client3 = new BluetoothClient(); client3.Connect(ep); // 打开串口通信 SerialPort serialPort = new SerialPort(); serialPort.PortName = "COM1"; // 选择一个未使用的串口号 serialPort.BaudRate = 9600; serialPort.Parity = Parity.None; serialPort.DataBits = 8; serialPort.StopBits = StopBits.One; serialPort.Open(); // 从蓝牙设备读取数据并输出到控制台 while (true) { if (serialPort.BytesToRead > 0) { Console.Write((char)serialPort.ReadByte()); } } // 关闭串口通信 serialPort.Close(); } else { Console.WriteLine("Device not found."); } Console.ReadLine(); } } } ``` 注意,你需要在项目中引用`InTheHand.Net.Personal.dll`和`InTheHand.Net.Sockets.dll`。此外,你需要将`MyDeviceName`替换为你要连接蓝牙设备的名称。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值