我想写两个ESP32经典蓝牙通信,发现多为蓝牙连接APP,也通过GPT写了一些,发现无法连接蓝牙。而CSDN上的很多优质教程需要付费。作为白嫖怪,我很头疼。
最后,知识付费。
现在把两个ESP32经典蓝牙通信最简代码,分享给大家。
环境:
arduino IDE或VS Code PlatformIO
一、硬件准备:
两个esp32。
二、代码功能:
简单功能介绍:服务端LED(D2)亮。
详细功能介绍:两个esp32下载好程序并通电,蓝牙自动连接,
客户端通过蓝牙发送字符 ‘A’ ;
服务端通过蓝牙接收后,控制LED(D2)亮。
三、服务端代码:
#include "BluetoothSerial.h"
#include <Arduino.h>
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif
// LED引脚
#define LED_PIN 2
BluetoothSerial SerialBT;
const char *pin = "1234"; // 蓝牙匹配代码,根据自己需要更改
String slaveName = "ESP32-BT-Slave"; // 蓝牙从机名称
String myName = "ESP32-BT-Master"; // 蓝牙主机名称
void setup() {
bool connected; // 布尔型变量,只有ture和flase两个值
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT); // 将LED引脚设置为输出模式
digitalWrite(LED_PIN, LOW); // 关闭LED
SerialBT.begin(myName, true); // 启动蓝牙串口
Serial.printf("The device \"%s\" started in master mode, make sure slave BT device is on!\n", myName.c_str());
SerialBT.setPin(pin); // 设置配对代码
Serial.println("Using PIN");
/*
connect(address) 很快(最多 10 秒),
connect(slaveName) 很慢(最多 30 秒),
根据需要。首先将 SlaveName 解析为地址,但它允许连接到具有相同名称的不同设备 .
设置CoreDebugLevel为Info可查看设备蓝牙地址和设备名称
*/
connected = SerialBT.connect(slaveName);
Serial.printf("Connecting to slave BT device named \"%s\"\n", slaveName.c_str());
if(connected) {
Serial.println("Connected Successfully!");
} else {
while(!SerialBT.connected(10000)) {
Serial.println("Failed to connect. Make sure remote device is available and in range, then restart app.");
}
}
}
void loop() {
// 读取接收到的字节并将其添加到消息(缓冲区)数组中
if (SerialBT.available()){
char command = SerialBT.read();
// command.trim(); // 去除字符串两端的空白字符
if (command == 'A')
{ // 如果接收到的命令是“ON”
digitalWrite(LED_PIN, HIGH); // 打开LED
Serial.println("LED is ON");
} else if (command == 'B')
{ // 如果接收到的命令是“OFF”
digitalWrite(LED_PIN, LOW); // 关闭LED
Serial.println("LED is OFF");
} else
{
Serial.println("Unknown command"); // 如果接收到未知命令
}
}
}
之前的代码之所以不能连接WiFi,原因之一是没有设置配对代码:
const char *pin = "1234"; // 蓝牙匹配代码,根据自己需要更改
SerialBT.setPin(pin); // 设置配对代码
四、客户端代码:
#include "BluetoothSerial.h"
#include <Arduino.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
#if !defined(CONFIG_BT_SPP_ENABLED)
#error Serial Bluetooth not available or not enabled. It is only available for the ESP32 chip.
#endif
// 蓝牙串口设备实例
BluetoothSerial SerialBT;
// SP32 蓝牙(从机)设备信息
const char *pin = "1234"; // 可以根据需要将其更改为更安全的 PIN。
String device_name = "ESP32-BT-Slave"; // 蓝牙设备名称
void setup() {
Serial.begin(115200);
SerialBT.begin(device_name); //启动蓝牙串口
Serial.printf("The device with name \"%s\" is started.\nNow you can pair it with Bluetooth!\n", device_name.c_str());
SerialBT.setPin(pin);
Serial.println("Using PIN");
}
void loop() {
SerialBT.println('A');
delay(100);
}