ESP32蓝牙接收手机指令异常:内置LED无法正常开关求助
ESP32蓝牙控制内置LED异常问题解决
问题情况
- 目标:通过Google Play商店的「Serial Bluetooth Terminal」APP发送ON/OFF指令,控制ESP32内置LED保持亮起或熄灭状态
- 异常:发送指令后LED仅短暂闪烁(疑似蓝牙接收提示),无法维持预期的亮/灭状态
- 前提:ESP32与手机已通过该APP正常建立蓝牙连接,指令发送正确
原错误代码
#include "BluetoothSerial.h" BluetoothSerial SerialBT; void setup() { Serial.begin(115200); if(!SerialBT.begin("ESP32")){ Serial.println("An error occurred initializing Bluetooth"); } } void loop() { while(SerialBT.available()){ Serial.println(SerialBT.read()); } delay(50); if (Serial.available()) { // if there is data coming String command = Serial.readStringUntil('\n'); // read string until newline character if (command == "ON") { digitalWrite(LED_BUILTIN, HIGH); // turn on LED Serial.println("Turn LED ON"); } else if (command == "OFF") { digitalWrite(LED_BUILTIN, LOW); // turn off LED Serial.println("Turn LED OFF"); } } }
问题分析
- 串口监听错误:代码中判断的是硬件串口
Serial的输入,而非蓝牙串口SerialBT,导致蓝牙APP发来的指令完全没被处理 - 数据提前消耗:开头的while循环把蓝牙串口的可用数据全部读取并打印,后续判断逻辑拿不到有效指令
- 未初始化LED引脚:未将
LED_BUILTIN设置为输出模式,部分ESP32型号无法正常驱动LED
修正后的代码
#include "BluetoothSerial.h" BluetoothSerial SerialBT; void setup() { Serial.begin(115200); // 初始化LED引脚为输出模式 pinMode(LED_BUILTIN, OUTPUT); if(!SerialBT.begin("ESP32")){ Serial.println("蓝牙初始化失败"); } else { Serial.println("蓝牙已启动,可搜索到ESP32"); } } void loop() { if (SerialBT.available()) { // 读取蓝牙发来的指令,直到换行符 String command = SerialBT.readStringUntil('\n'); // 去除字符串首尾的空白字符(避免APP发送的换行/空格干扰) command.trim(); if (command == "ON") { digitalWrite(LED_BUILTIN, HIGH); Serial.println("LED已开启"); SerialBT.println("LED已开启"); // 给APP返回反馈 } else if (command == "OFF") { digitalWrite(LED_BUILTIN, LOW); Serial.println("LED已关闭"); SerialBT.println("LED已关闭"); // 给APP返回反馈 } } delay(10); // 小幅延迟降低资源占用 }
额外注意事项
- 在「Serial Bluetooth Terminal」APP中发送指令时,确保勾选「Append newline」选项(自动添加换行符),否则
readStringUntil('\n')会一直等待数据 - 部分ESP32的内置LED是低电平点亮,若修正后LED状态相反,可将
HIGH和LOW互换
内容的提问来源于stack exchange,提问作者FrShr
相关产品推荐
相关产品推荐

