这些使用c# .net8开发,硬件 香橙派 orangepi 3lts和 hc-04蓝牙
使用场景:可以通过这个功能,手机连接orangepi进行wifi等参数配置
硬件:
1、带USB口的linux开发板orangepi
2、USB 转TTL 中转接蓝牙(HC-04)
某宝上买的蓝牙官方网有调试工具:HC-T串口助手
https://www.hc01.com/downloads
也有手机端的调试工具
电脑和手机上调试成功后,证明蓝牙是正常使用的
.net 8代码
- using System.IO.Ports;
-
- public class UtilsSerial
- {
-
- public void test()
- {
- getDataAndWriteString("/dev/ttyUSB0", 9600, "test");
- ///dev/ttyUSB0 是在香橙派运行上的端口
- //COM8 是本地window运行的端口
- }
-
- static SerialPort portString = null;
- /// <summary>
- /// 串口调用,适用于蓝牙模块hc-04通讯
- /// </summary>
- public void getDataAndWriteString(string portName, int baudRate,string content)
- {
- if (portString == null)
- {
- portString = new SerialPort(portName);
- portString.BaudRate = baudRate;
- portString.DataBits = 8;
- portString.Parity = Parity.None;
- portString.StopBits = StopBits.One;
- portString.Open();
- portString.DataReceived += getDataAndWriteStringPortDataReceived;
- Console.WriteLine("Serial Is Open");
- }
- if (portString.IsOpen)
- {
- // 将字符串转换为字节数组并写入串口
- byte[] dataBytes = Encoding.ASCII.GetBytes(content);
- portString.Write(dataBytes, 0, dataBytes.Length);
- }
- }
- private void getDataAndWriteStringPortDataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- var s = sender as SerialPort;
- if(s.BytesToRead> 0)
- {
- Thread.Sleep(50);
- }
- byte[] recData = new byte[s.BytesToRead];
- s.Read(recData, 0, recData.Length);
- var str = Encoding.Default.GetString(recData);
- Console.WriteLine(str);
- }
- }
USB连接香橙派后 查看串口情况
ls -l /dev/tty* #查看串口
可以看到USB0已连接
在香橙派orangepi 上运行,接收到手机APP调试工具发送的内容