#include "BluetoothSerial.h"
#define BUILTIN_LED 2 // Define the GPIO pin for the built-in LED (often GPIO 2)
// Bluetooth Serial Object (Handle)
BluetoothSerial SerialBT;
// ESP32 Bluetooth (Slave) Device Information
const char *pin = "1234"; // Change this to a more secure PIN.
String device_name = "ESP32-BT-Slave";
// Bluetooth Received Byte & Message Buffer Array
String RxBuffer = "";
char RxByte;
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Use defined GPIO pin for the built-in LED
Serial.begin(115200);
SerialBT.begin(device_name); // Bluetooth 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() {
// Read The Received Bytes & Add Them To Message (RxBuffer) Array
if (SerialBT.available()){
RxByte = SerialBT.read();
if (RxByte != '\n'){
RxBuffer += String(RxByte);
}
else{
RxBuffer = "";
}
Serial.write(RxByte);
}
// Check The Received Message & Update Output LED State
if (RxBuffer == "led_on"){
digitalWrite(BUILTIN_LED, HIGH); // Turn on the built-in LED
}
else if (RxBuffer == "led_off"){
digitalWrite(BUILTIN_LED, LOW); // Turn off the built-in LED
}
delay(25);
}