ESP32 Bluetooth serial lamp
BluetoothSerial on the ESP32: pair with ESP32-Lamp in the Bluetooth tab, send on or off, and the LED answers. The phone is simulated, the sketch is real. The whole build, an ESP32 DevKit and 2 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The parts retail for about $9.15. On Mokxi they're free.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Bluetooth lamp: the ESP32's own Bluetooth serial port switches an LED.
//
// Simulated Bluetooth: a phone in Mokxi, not a real radio. Press Run, open
// the Bluetooth tab, pair with ESP32-Lamp and connect, then send on, off or
// status. The same sketch runs unchanged on a real ESP32 with the "Serial
// Bluetooth Terminal" app on a phone.
#include "BluetoothSerial.h"
BluetoothSerial SerialBT;
const int kLed = 4; // an LED and a resistor to ground
void onBluetooth(esp_spp_cb_event_t event, esp_spp_cb_param_t *param)
{
if (event == ESP_SPP_SRV_OPEN_EVT) {
Serial.println("A phone connected.");
SerialBT.println("Hello from ESP32-Lamp. Send on, off or status.");
} else if (event == ESP_SPP_CLOSE_EVT) {
Serial.println("The phone disconnected.");
}
}
void setup()
{
Serial.begin(115200);
pinMode(kLed, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
SerialBT.register_callback(onBluetooth);
SerialBT.begin("ESP32-Lamp");
Serial.println("ESP32-Lamp is ready: pair with it from the Bluetooth tab.");
}
void loop()
{
// The blue LED on the board shows whether a phone is connected.
digitalWrite(LED_BUILTIN, SerialBT.hasClient() ? HIGH : LOW);
if (SerialBT.available()) {
String line = SerialBT.readStringUntil('\n');
line.trim();
line.toLowerCase();
Serial.print("Phone sent: ");
Serial.println(line);
if (line == "on") {
digitalWrite(kLed, HIGH);
SerialBT.println("The lamp is on.");
} else if (line == "off") {
digitalWrite(kLed, LOW);
SerialBT.println("The lamp is off.");
} else if (line == "status") {
SerialBT.println(digitalRead(kLed) ? "The lamp is on." : "The lamp is off.");
} else if (line.length() > 0) {
SerialBT.println("Send on, off or status.");
}
}
delay(20);
}
Parts list
3 parts, plus the jumper wires. They retail for about $9.15; on Mokxi they're free.
- 1 × ESP32 DevKit V1
- 1 × Resistor, 220 Ω
- 1 × LED, yellow
How it is wired
3 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- ESP32 DevKit V1 pin D4; Resistor, 220 Ω pin 1
- Resistor, 220 Ω pin 2; LED, yellow pin A
- Ground: LED, yellow pin C
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.