ESP32 Bluetooth 서보 잠금장치
SG90 서보를 작은 걸쇠로 삼아 휴대폰에서 Bluetooth로 조종해요. 잠그고, 열고, 각도를 정하는데 인터넷도 Wi-Fi도 필요 없어요. 이 프로젝트는 앱의 서보 잠금장치 Bluetooth 템플릿을 단계별로 안내하는 가이드로, ESP32, 서보 하나, 전선 3가닥으로 만들어요. 내 작업실 › 내 기기 › 기기 추가 › Bluetooth로 가서 서보 잠금장치를 고르고 코드 받기로 코드를 업로드하세요. 이 페이지의 Bluetooth 패널로 설정 버튼으로도 이 템플릿으로 마법사가 열려요.

동영상
회로도

소스 코드
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}
204FAQ
iPhone에서도 돼요?
네. ESP32의 내장 Bluetooth Low Energy(BLE)는 iPhone, Android와 모두 통신해요. iPhone은 HC-05나 HC-06 같은 클래식 Bluetooth 모듈에 연결할 수 없고, 이 프로젝트에는 그런 모듈이 필요 없어요. 휴대폰의 Bluetooth 설정에서 보드를 페어링하려고 하지 마세요. BLE 보드는 거기에 안 보일 수 있고, 그게 정상이에요. 연결은 BlueGrays 앱이 해요.
연결이 끊기면 왜 저절로 잠겨요?
일부러 그렇게 만들었어요. 코드의 LOCK_ON_DISCONNECT 설정이 true라서, 휴대폰이 범위를 벗어나거나 앱이 닫히면 보드가 걸쇠를 잠금 각도(90도)로 되돌려요. 그래서 실수로 잠금장치가 열린 채로 남지 않아요. 보드는 전원이 켜질 때도 잠긴 상태로 시작해요. 열린 채로 두고 싶으면 그 값을 false로 바꾸고 코드를 다시 업로드하세요. 잠금 스위치 대신 서보 각도 슬라이더로 걸쇠를 열었을 때도 같은 보호가 작동해요. 보드는 90도가 아닌 모든 각도를 열림으로 봐요.
진짜 문이나 금고를 잠글 수 있어요?
아니요, 이건 학습 프로젝트예요. SG90은 플라스틱 기어가 든 작은 취미용 서보라서, 힘을 주면 혼이 돌아가고 전원이 끊기면 붙잡는 힘이 전혀 없어요. 게다가 이 코드의 Bluetooth 연결에는 비밀번호가 없어서, 근처의 다른 휴대폰도 보드에 연결해 명령을 보낼 수 있어요. 상자, 서랍, 모형 문의 걸쇠로 시험해 보고, 진짜 문이나 귀중품을 맡기지는 마세요.
잠금 스위치와 각도 슬라이더는 무엇이 달라요?
잠금 스위치는 걸쇠를 코드에 적힌 두 위치로 움직여요. 잠금은 90도, 열림은 0도예요. 바뀔 때마다 보드가 새 각도를 패널에 알려 주기 때문에 슬라이더도 그 값으로 이동해요. 서보 각도 슬라이더는 대신 혼을 0~180도 사이 어디로든 돌려요. 걸쇠가 실제로 어디서 잠기는지 찾을 때 편리해요. 찾은 값은 코드의 LOCKED_ANGLE과 OPEN_ANGLE 줄에 쓰세요. 슬라이더를 90도가 아닌 각도로 옮기면 보드는 잠금장치가 열렸다고 보고, 패널의 잠금 스위치도 그렇게 보여 줘요. 정확히 90도로 돌아오면 다시 잠김으로 나와요.
