ESP32 Bluetooth Cerradura con servo
Maneja un servo SG90 como un pequeño pestillo desde tu móvil por Bluetooth: ciérralo, ábrelo o ajusta el ángulo, sin internet ni wifi. Este proyecto es la guía paso a paso de la plantilla Bluetooth Cerradura con servo de la app: un ESP32, un servo y 3 cables. Ve a Mi Taller › Dispositivos › Añadir dispositivo › Bluetooth, elige esa plantilla y sube el código con Obtener el código. El botón Configurar como panel Bluetooth de esta página abre el mismo asistente.

Video
Diagrama del circuito

Código fuente
1// ┌───────────────────────────┐
2// │ BlueGrays · bluegrays.com │
3// │ Bluetooth · ESP32 │
4// │ BG-Kilit │
5// └───────────────────────────┘
6// Cerradura con servo
7// Placa en Arduino IDE: ESP32 Dev Module
8// la biblioteca BLE viene con el paquete de placas ESP32, no hay que instalar nada más
9
10#include <BLEDevice.h>
11#include <BLEServer.h>
12#include <BLE2902.h>
13#include <ESP32Servo.h> // Gestor de bibliotecas: 'ESP32Servo'
14
15const char BLE_NAME[] = "BG-Kilit"; // la placa se anuncia con este nombre y la app la encuentra así en la lista
16
17// Pines: cámbialos aquí si conectaste de otra forma
18const int SERVO_PIN = 13;
19const int LOCKED_ANGLE = 90, OPEN_ANGLE = 0; // ángulos del servo para cerrado y abierto
20const bool LOCK_ON_DISCONNECT = true; // Si se corta la conexión, la cerradura se cierra (pon false para dejarla como está)
21
22void btWrite(const char *text);
23void onValue(const char *key, const char *value);
24void sendAll();
25void onLinkLost();
26
27// ── La app envía líneas "clave=valor"; con "?" la placa manda todos sus valores ──
28char line[65];
29uint8_t lineLen = 0;
30unsigned long lastRxMs = 0;
31
32bool is(const char *a, const char *b) { return strcmp(a, b) == 0; }
33bool isOn(const char *v) { return v[0] == '1'; }
34
35void sendText(const char *key, const char *value) {
36 char out[72];
37 snprintf(out, sizeof(out), "%s=%s\n", key, value);
38 btWrite(out);
39}
40
41void sendInt(const char *key, long value) {
42 char text[12];
43 snprintf(text, sizeof(text), "%ld", value);
44 sendText(key, text);
45}
46
47void sendFloat(const char *key, float value) {
48 char text[16];
49 dtostrf(value, 1, 1, text);
50 sendText(key, text);
51}
52
53void handleLine(char *text) {
54 char *eq = strchr(text, '=');
55 if (eq == nullptr) {
56 if (text[strlen(text) - 1] == '?') {
57 btWrite("@v=1.0\n"); // la línea "@v" indica a la app la versión del código
58 sendAll();
59 }
60 return;
61 }
62 *eq = '\0';
63 onValue(text, eq + 1);
64}
65
66void feed(char c) {
67 lastRxMs = millis();
68 if (c == '\n' || c == '\r') {
69 if (lineLen == 0) return;
70 line[lineLen] = '\0';
71 lineLen = 0;
72 handleLine(line);
73 } else if (lineLen < sizeof(line) - 1) {
74 line[lineLen++] = c;
75 }
76}
77
78// ── Bluetooth (Nordic UART) ──
79#define UART_SERVICE "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
80#define UART_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
81#define UART_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
82
83BLECharacteristic *txChar = nullptr;
84volatile bool linked = false;
85volatile bool linkLost = false;
86// los bytes que llegan pasan de la tarea Bluetooth a loop() por un pequeño búfer circular
87const int RX_SIZE = 256;
88volatile uint8_t rxBuf[RX_SIZE];
89volatile int rxHead = 0, rxTail = 0;
90
91class ServerEvents : public BLEServerCallbacks {
92 void onConnect(BLEServer *server) override { linked = true; }
93 void onDisconnect(BLEServer *server) override { linked = false; linkLost = true; }
94};
95
96class RxEvents : public BLECharacteristicCallbacks {
97 void onWrite(BLECharacteristic *c) override {
98 auto v = c->getValue();
99 for (size_t i = 0; i < v.length(); i++) {
100 int next = (rxHead + 1) % RX_SIZE;
101 if (next == rxTail) break;
102 rxBuf[rxHead] = (uint8_t)v[i];
103 rxHead = next;
104 }
105 }
106};
107
108// las líneas salen en paquetes de 20 bytes (funciona con cualquier móvil)
109void btWrite(const char *text) {
110 if (!linked || txChar == nullptr) return;
111 size_t n = strlen(text);
112 for (size_t i = 0; i < n; i += 20) {
113 size_t len = n - i < 20 ? n - i : 20;
114 txChar->setValue((uint8_t *)text + i, len);
115 txChar->notify();
116 delay(4);
117 }
118}
119
120void btBegin() {
121 BLEDevice::init(BLE_NAME);
122 BLEServer *server = BLEDevice::createServer();
123 server->setCallbacks(new ServerEvents());
124 BLEService *uart = server->createService(UART_SERVICE);
125 txChar = uart->createCharacteristic(UART_TX, BLECharacteristic::PROPERTY_NOTIFY);
126 txChar->addDescriptor(new BLE2902());
127 BLECharacteristic *rx = uart->createCharacteristic(UART_RX, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR);
128 rx->setCallbacks(new RxEvents());
129 uart->start();
130 BLEAdvertisementData adv;
131 adv.setFlags(0x06);
132 adv.setCompleteServices(BLEUUID(UART_SERVICE));
133 BLEAdvertisementData scan;
134 scan.setName(BLE_NAME);
135 BLEAdvertising *advertising = BLEDevice::getAdvertising();
136 advertising->setAdvertisementData(adv);
137 advertising->setScanResponseData(scan);
138 BLEDevice::startAdvertising();
139}
140
141void btPoll() {
142 while (rxTail != rxHead) {
143 char c = (char)rxBuf[rxTail];
144 rxTail = (rxTail + 1) % RX_SIZE;
145 feed(c);
146 }
147 if (linkLost) {
148 linkLost = false;
149 onLinkLost();
150 delay(100);
151 BLEDevice::startAdvertising();
152 }
153}
154
155// ── ESP32 ──
156Servo servo;
157bool locked = true;
158int angle = LOCKED_ANGLE;
159
160void moveTo(int a) {
161 angle = constrain(a, 0, 180);
162 servo.write(angle);
163}
164
165void onValue(const char *key, const char *value) {
166 if (is(key, "kilit")) {
167 locked = isOn(value);
168 moveTo(locked ? LOCKED_ANGLE : OPEN_ANGLE);
169 sendInt("aci", angle);
170 } else if (is(key, "aci")) {
171 moveTo(atoi(value));
172 if (locked != (angle == LOCKED_ANGLE)) {
173 locked = !locked;
174 sendInt("kilit", locked);
175 }
176 }
177}
178
179void sendAll() {
180 sendInt("kilit", locked);
181 sendInt("aci", angle);
182}
183
184void onLinkLost() {
185 if (LOCK_ON_DISCONNECT && !locked) {
186 locked = true;
187 moveTo(LOCKED_ANGLE);
188 }
189}
190
191void setup() {
192 Serial.begin(115200);
193 servo.setPeriodHertz(50);
194 servo.attach(SERVO_PIN, 500, 2500);
195 moveTo(LOCKED_ANGLE);
196 btBegin();
197 Serial.print(F("BlueGrays Bluetooth: "));
198 Serial.println(BLE_NAME);
199}
200
201void loop() {
202 btPoll();
203}
204Preguntas frecuentes
¿Funciona con iPhone?
Sí. El Bluetooth Low Energy (BLE) integrado del ESP32 habla con iPhone y con Android. Un iPhone no puede conectarse a módulos de Bluetooth clásico como el HC-05 y el HC-06, y este proyecto no los necesita. No intentes emparejar la placa desde los ajustes Bluetooth del móvil; las placas BLE pueden no aparecer ahí, es normal. La conexión la hace la app BlueGrays.
¿Por qué se cierra sola cuando se corta la conexión?
Es a propósito. Como el ajuste LOCK_ON_DISCONNECT del código está en true, la placa devuelve el pestillo al ángulo de cierre (90 grados) cuando el móvil se aleja o se cierra la app; así la cerradura no se queda abierta por descuido. La placa también arranca cerrada al encenderse. Si prefieres que se quede abierta, pon ese valor en false y vuelve a subir el código. La misma protección actúa si abriste el pestillo con el deslizador Ángulo del servo en lugar del interruptor Cerradura: la placa da por abierto cualquier ángulo distinto de 90.
¿Puedo cerrar con esto una puerta de verdad o una caja fuerte?
No, es un proyecto para aprender. El SG90 es un servo pequeño de hobby con engranajes de plástico; el brazo gira si lo fuerzas y, sin alimentación, ya no opone resistencia. Además, la conexión Bluetooth de este código no lleva contraseña: otro móvil cercano también puede conectarse a la placa y enviarle órdenes. Pruébalo en el pestillo de una caja, un cajón o una puerta de maqueta; no le confíes una puerta real ni objetos de valor.
¿En qué se diferencian el interruptor y el deslizador de ángulo?
El interruptor Cerradura lleva el pestillo a dos posiciones escritas en el código: cerrado a 90 grados y abierto a 0. En cada cambio la placa comunica el nuevo ángulo al panel y el deslizador salta a ese valor. El deslizador Ángulo del servo, en cambio, gira el brazo a cualquier punto entre 0 y 180 grados; viene bien para descubrir dónde cierra de verdad tu pestillo. Anota los valores que encuentres en las líneas LOCKED_ANGLE y OPEN_ANGLE del código. Si llevas el deslizador a un ángulo distinto de 90, la placa da la cerradura por abierta y el interruptor Cerradura del panel también lo muestra; al volver justo a 90 aparece cerrada de nuevo.
