ES-111Beginner

ESP32 Bluetooth Servo Lock

Control an SG90 servo as a small latch from your phone over Bluetooth: lock, open or set the angle, no internet or Wi-Fi needed. This project is the step-by-step guide to the Servo lock Bluetooth template in the app, built with an ESP32, one servo and 3 wires. Go to Workshop › Devices › Add a device › Bluetooth, pick Servo lock and upload the code with Get the code. The Set up as a Bluetooth panel button on this page opens the wizard with this template too.

0.0(0)
ESP32 Bluetooth Servo Lock
Tap the lock switch on your phone and the servo turns to 90 degrees and closes the latch; tap again and it opens at 0. No internet or router: the phone connects straight to the ESP32 over Bluetooth. A slider sets any angle from 0 to 180 degrees. The board starts locked and, if the lock is open when the link drops, locks itself again. The SG90 is a small hobby servo: this is a learning project for a box, drawer or model door latch, not a substitute for a real door lock or a lock for valuables. In the app, pick Bluetooth and the Servo lock template, upload with Get the code and find your board in the list. Learning: servo angles, short text lines over Bluetooth Low Energy and a board that reports its state.

Video

Circuit Diagram

ESP32 Bluetooth Servo Lock - Circuit Diagram

Source Code

C++ (Arduino IDE)
1// ┌───────────────────────────┐
2// │ BlueGrays · bluegrays.com │
3// │ Bluetooth · ESP32         │
4// │ BG-Kilit                  │
5// └───────────────────────────┘
6// Servo lock
7// Arduino IDE board: ESP32 Dev Module
8// the BLE library comes with the ESP32 board package, nothing extra to install
9
10#include <BLEDevice.h>
11#include <BLEServer.h>
12#include <BLE2902.h>
13#include <ESP32Servo.h>  // Library Manager: 'ESP32Servo'
14
15const char BLE_NAME[] = "BG-Kilit";  // the board advertises with this name, the app finds it in the list by it
16
17// Pins: change them here if you wired differently
18const int SERVO_PIN = 13;
19const int LOCKED_ANGLE = 90, OPEN_ANGLE = 0;  // servo angles for locked and open
20const bool LOCK_ON_DISCONNECT = true;  // If the connection drops the lock closes (set false to leave it as it is)
21
22void btWrite(const char *text);
23void onValue(const char *key, const char *value);
24void sendAll();
25void onLinkLost();
26
27// ── The app sends "key=value" lines; on "?" the board sends all its values ──
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");  // the "@v" line tells the app the code version
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// incoming bytes move from the Bluetooth task to loop() through a small ring buffer
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// lines go out in 20-byte packets (works with every phone)
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}
204

FAQ

Does it work with an iPhone?

Yes. The ESP32's built-in Bluetooth Low Energy (BLE) talks to both iPhone and Android. An iPhone cannot connect to classic Bluetooth modules like the HC-05 and HC-06, and this project does not need them. Do not try to pair the board in your phone's Bluetooth settings; BLE boards may not show up there, which is normal. The BlueGrays app makes the connection.

Why does it lock by itself when the connection drops?

That is on purpose. Because the LOCK_ON_DISCONNECT setting in the code is true, the board turns the latch back to the locked angle (90 degrees) when the phone moves out of range or the app is closed, so the lock is not left open by accident. The board also starts locked when it powers up. If you want it to stay open, set that value to false and upload the code again. The same protection works if you opened the latch with the Servo angle slider instead of the Lock switch: the board counts any angle other than 90 as open.

Can I lock a real door or a safe with it?

No, this is a learning project. The SG90 is a small hobby servo with plastic gears; its horn turns if you force it, and once power is cut it has no holding force left. On top of that, the Bluetooth link in this code has no password: another phone nearby can connect to the board and send commands too. Try it on the latch of a box, a drawer or a model door; do not trust it with a real door or with valuables.

What is the difference between the lock switch and the angle slider?

The Lock switch moves the latch to two positions written in the code: locked at 90 degrees, open at 0. On every change the board reports the new angle to the panel, so the slider jumps to that value. The Servo angle slider turns the horn anywhere between 0 and 180 degrees instead; it is handy for finding where your latch really closes. Write the values you find into the LOCKED_ANGLE and OPEN_ANGLE lines of the code. When you move the slider to any angle other than 90 the board counts the lock as open and the Lock switch in the panel shows that too; back at exactly 90 it shows locked again.