ESP32 Bluetooth LED와 릴레이
인터넷이나 Wi-Fi 없이 휴대폰에서 Bluetooth로 LED와 릴레이를 켜고 꺼요. 이 프로젝트는 앱의 LED와 릴레이 Bluetooth 템플릿을 단계별로 안내하는 가이드로, ESP32와 5 V 릴레이 모듈로 만들어요. 내 작업실 › 내 기기 › 기기 추가 › Bluetooth로 가서 LED와 릴레이를 고르고 코드 받기로 코드를 업로드하세요. 이 페이지의 Bluetooth 패널로 설정 버튼으로도 이 템플릿으로 마법사가 열려요.

동영상
회로도

소스 코드
1// ┌───────────────────────────┐
2// │ BlueGrays · bluegrays.com │
3// │ Bluetooth · ESP32 │
4// │ BG-Lamba │
5// └───────────────────────────┘
6// LED and relay
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
14const char BLE_NAME[] = "BG-Lamba"; // the board advertises with this name, the app finds it in the list by it
15
16// Pins: change them here if you wired differently
17const int LED_PIN = 2;
18const int RELAY_PIN = 26;
19const bool RELAY_ACTIVE_LOW = true; // most relay modules switch on LOW
20
21void btWrite(const char *text);
22void onValue(const char *key, const char *value);
23void sendAll();
24void onLinkLost();
25
26// ── The app sends "key=value" lines; on "?" the board sends all its values ──
27char line[65];
28uint8_t lineLen = 0;
29unsigned long lastRxMs = 0;
30
31bool is(const char *a, const char *b) { return strcmp(a, b) == 0; }
32bool isOn(const char *v) { return v[0] == '1'; }
33
34void sendText(const char *key, const char *value) {
35 char out[72];
36 snprintf(out, sizeof(out), "%s=%s\n", key, value);
37 btWrite(out);
38}
39
40void sendInt(const char *key, long value) {
41 char text[12];
42 snprintf(text, sizeof(text), "%ld", value);
43 sendText(key, text);
44}
45
46void sendFloat(const char *key, float value) {
47 char text[16];
48 dtostrf(value, 1, 1, text);
49 sendText(key, text);
50}
51
52void handleLine(char *text) {
53 char *eq = strchr(text, '=');
54 if (eq == nullptr) {
55 if (text[strlen(text) - 1] == '?') {
56 btWrite("@v=1.0\n"); // the "@v" line tells the app the code version
57 sendAll();
58 }
59 return;
60 }
61 *eq = '\0';
62 onValue(text, eq + 1);
63}
64
65void feed(char c) {
66 lastRxMs = millis();
67 if (c == '\n' || c == '\r') {
68 if (lineLen == 0) return;
69 line[lineLen] = '\0';
70 lineLen = 0;
71 handleLine(line);
72 } else if (lineLen < sizeof(line) - 1) {
73 line[lineLen++] = c;
74 }
75}
76
77// ── Bluetooth (Nordic UART) ──
78#define UART_SERVICE "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
79#define UART_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
80#define UART_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
81
82BLECharacteristic *txChar = nullptr;
83volatile bool linked = false;
84volatile bool linkLost = false;
85// incoming bytes move from the Bluetooth task to loop() through a small ring buffer
86const int RX_SIZE = 256;
87volatile uint8_t rxBuf[RX_SIZE];
88volatile int rxHead = 0, rxTail = 0;
89
90class ServerEvents : public BLEServerCallbacks {
91 void onConnect(BLEServer *server) override { linked = true; }
92 void onDisconnect(BLEServer *server) override { linked = false; linkLost = true; }
93};
94
95class RxEvents : public BLECharacteristicCallbacks {
96 void onWrite(BLECharacteristic *c) override {
97 auto v = c->getValue();
98 for (size_t i = 0; i < v.length(); i++) {
99 int next = (rxHead + 1) % RX_SIZE;
100 if (next == rxTail) break;
101 rxBuf[rxHead] = (uint8_t)v[i];
102 rxHead = next;
103 }
104 }
105};
106
107// lines go out in 20-byte packets (works with every phone)
108void btWrite(const char *text) {
109 if (!linked || txChar == nullptr) return;
110 size_t n = strlen(text);
111 for (size_t i = 0; i < n; i += 20) {
112 size_t len = n - i < 20 ? n - i : 20;
113 txChar->setValue((uint8_t *)text + i, len);
114 txChar->notify();
115 delay(4);
116 }
117}
118
119void btBegin() {
120 BLEDevice::init(BLE_NAME);
121 BLEServer *server = BLEDevice::createServer();
122 server->setCallbacks(new ServerEvents());
123 BLEService *uart = server->createService(UART_SERVICE);
124 txChar = uart->createCharacteristic(UART_TX, BLECharacteristic::PROPERTY_NOTIFY);
125 txChar->addDescriptor(new BLE2902());
126 BLECharacteristic *rx = uart->createCharacteristic(UART_RX, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR);
127 rx->setCallbacks(new RxEvents());
128 uart->start();
129 BLEAdvertisementData adv;
130 adv.setFlags(0x06);
131 adv.setCompleteServices(BLEUUID(UART_SERVICE));
132 BLEAdvertisementData scan;
133 scan.setName(BLE_NAME);
134 BLEAdvertising *advertising = BLEDevice::getAdvertising();
135 advertising->setAdvertisementData(adv);
136 advertising->setScanResponseData(scan);
137 BLEDevice::startAdvertising();
138}
139
140void btPoll() {
141 while (rxTail != rxHead) {
142 char c = (char)rxBuf[rxTail];
143 rxTail = (rxTail + 1) % RX_SIZE;
144 feed(c);
145 }
146 if (linkLost) {
147 linkLost = false;
148 onLinkLost();
149 delay(100);
150 BLEDevice::startAdvertising();
151 }
152}
153
154// ── ESP32 ──
155bool ledOn = false, relayOn = false;
156
157void setRelay(bool on) {
158 if (RELAY_ACTIVE_LOW) {
159 if (on) { pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, LOW); }
160 else { pinMode(RELAY_PIN, INPUT); } // off releases the pin: a 3.3 V HIGH is not enough to turn a 5 V module off
161 } else {
162 pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, on ? HIGH : LOW);
163 }
164}
165
166void apply() {
167 digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
168 setRelay(relayOn);
169}
170
171void onValue(const char *key, const char *value) {
172 if (is(key, "led")) ledOn = isOn(value);
173 else if (is(key, "role")) relayOn = isOn(value);
174 apply();
175}
176
177void sendAll() {
178 sendInt("led", ledOn);
179 sendInt("role", relayOn);
180}
181
182void onLinkLost() {
183}
184
185void setup() {
186 Serial.begin(115200);
187 pinMode(LED_PIN, OUTPUT);
188 apply();
189 btBegin();
190 Serial.print(F("BlueGrays Bluetooth: "));
191 Serial.println(BLE_NAME);
192}
193
194void loop() {
195 btPoll();
196}
197FAQ
iPhone에서도 돼요?
네. ESP32의 내장 Bluetooth Low Energy(BLE)는 iPhone, Android와 모두 통신해요. iPhone은 HC-05나 HC-06 같은 클래식 Bluetooth 모듈에 연결할 수 없고, 이 프로젝트에는 그런 모듈이 필요 없어요. 휴대폰의 Bluetooth 설정에서 보드를 페어링하려고 하지 마세요. BLE 보드는 거기에 안 보일 수 있고, 그게 정상이에요. 연결은 BlueGrays 앱이 해요.
릴레이에 진짜 전등을 연결해도 돼요?
릴레이 모듈은 상용 전압을 켜고 끌 수 있지만, 상용 전원은 목숨을 앗아 갈 수 있어요. 이 프로젝트에서는 릴레이의 COM과 NO 단자에 아무것도 연결하지 않고, 릴레이가 딸깍 소리와 모듈 LED로 작동을 보여 줘요. 부하를 연결해 보고 싶다면 배터리나 12 V 어댑터 같은 저전압 회로부터 시작하세요. 상용 전원으로 넘어간다면 경험 있는 사람과 함께 하고, 드러난 전선이나 나사를 남기지 말고, 모듈에 인쇄된 정격 전류를 넘지 마세요.
보드의 파란 LED가 왜 내 LED와 함께 켜져요?
많은 ESP32 DevKit 보드에서 보드의 파란 LED도 GPIO2에 연결되어 있어요. 내 LED가 같은 핀에 있어서 둘이 함께 깜박이는 거예요. 고장이 아니에요. 오히려 편리해요. 전선이 헐거워도 파란 LED가 명령이 보드에 도착했다는 걸 보여 줘요. 원하지 않으면 LED를 다른 핀(예: GPIO4)으로 옮기고 코드의 LED_PIN을 바꾸세요.
인터넷이나 Wi-Fi가 필요해요? 범위는 얼마나 돼요?
아니요. 휴대폰이 공유기나 서버 없이 Bluetooth로 보드에 바로 연결돼요. 실내에서 범위는 보통 10미터 정도이고, 벽이 있으면 짧아져요. 보드는 한 번에 휴대폰 하나와 연결돼요. 그 휴대폰이 떠나면 보드가 다시 광고 신호를 보내고 다른 휴대폰이 연결할 수 있어요. 집 밖에서 조종하려면 앱의 Wi-Fi IoT 패널을 쓰는 프로젝트를 고르세요.
