一、经典蓝牙
ESP32 上的内置经典蓝牙相比低功耗蓝牙较为简单,可以和 Android 智能手机之间交换数据。例程手机蓝牙控制 led 开关:
#include "BluetoothSerial.h" //引入蓝牙函数库
// 检查蓝牙是否正确启用
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
const int ledPin = 2;
String message = "";
BluetoothSerial SerialBT; // 蓝牙结构名称
void setup()
{
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin , LOW);
SerialBT.begin("ESP32_Blue"); // 蓝牙名称
Serial.println("The device started, now you can pair it with bluetooth!");
}
void loop()
{
if (SerialBT.available()) //判断蓝牙串口是否收到数据
{
char c = SerialBT.read(); //将收到的数据读取出来,下面分别处理
// String res = SerialBT.readString(); //将收到的数据读取出来,下面分别处理
if (c != '\n')
{
message += String(c);
}
else
{
message = "";
}
Serial.write(c);
}
if (message == "led_on")
{
digitalWrite(ledPin, HIGH);
}
else if (message == "led_off")
{
digitalWrite(ledPin, LOW);
}
delay(10);
}
烧录到 ESP32 开发板后,可以在手机端用蓝牙串口工具连接到 ESP32 蓝牙