ES-112초급

ESP32 Bluetooth LCD에 글자 표시

휴대폰에서 메시지를 입력하면 Bluetooth로 16x2 LCD에 나와요. 인터넷도 Wi-Fi도 필요 없어요. 이 프로젝트는 앱의 LCD에 글자 표시 Bluetooth 템플릿을 단계별로 안내하는 가이드로, ESP32와 I2C LCD로 만들어요. 내 작업실 › 내 기기 › 기기 추가 › Bluetooth로 가서 LCD에 글자 표시를 고르고 코드 받기로 코드를 업로드하세요. 이 페이지의 Bluetooth 패널로 설정 버튼으로도 이 템플릿으로 마법사가 열려요.

0.0(0)
ESP32 Bluetooth LCD에 글자 표시
휴대폰에서 메시지를 입력하고 보내기를 누르면, 인터넷이나 서버 없이 책상 위의 LCD에 나타나요. ESP32에는 Bluetooth가 내장되어 있어서 휴대폰이 보드에 바로 연결되고, 디스플레이의 I2C 모듈은 전선 4가닥만 있으면 돼요. 16x2 디스플레이에는 32글자가 들어가요. 위쪽 줄에 16글자, 나머지는 아래쪽 줄이에요. 코드는 é, ü, ñ 같은 악센트 문자를 기본 라틴 문자로 바꾸고, 모르는 문자는 물음표로 보여 줘요. 패널의 백라이트 스위치로 불을 켜고 꺼요. 앱에서 LCD에 글자 표시 템플릿을 고르고, 코드를 업로드한 다음 목록에서 보드를 찾으세요. 배우는 것: Bluetooth Low Energy로 텍스트 보내기, I2C LCD 구동하기, 텍스트를 줄로 나누기, 문자 변환 표.

동영상

회로도

ESP32 Bluetooth LCD에 글자 표시 - 회로도

소스 코드

C++ (Arduino IDE)
1// ┌───────────────────────────┐
2// │ BlueGrays · bluegrays.com │
3// │ Bluetooth · ESP32         │
4// │ BG-Ekran                  │
5// └───────────────────────────┘
6// Text on an LCD
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 <Wire.h>
14#include <LiquidCrystal_I2C.h>  // Library Manager: 'LiquidCrystal I2C' (Frank de Brabander)
15
16const char BLE_NAME[] = "BG-Ekran";  // the board advertises with this name, the app finds it in the list by it
17
18// Pins: change them here if you wired differently
19const int SDA_PIN = 21, SCL_PIN = 22;
20const int LCD_COLS = 16, LCD_ROWS = 2;  // LCD size: columns × rows
21const uint8_t LCD_ADDRESS = 0x27;  // most I2C LCD backpacks use 0x27; try 0x3F if the screen stays blank
22
23void btWrite(const char *text);
24void onValue(const char *key, const char *value);
25void sendAll();
26void onLinkLost();
27
28// ── The app sends "key=value" lines; on "?" the board sends all its values ──
29char line[65];
30uint8_t lineLen = 0;
31unsigned long lastRxMs = 0;
32
33bool is(const char *a, const char *b) { return strcmp(a, b) == 0; }
34bool isOn(const char *v) { return v[0] == '1'; }
35
36void sendText(const char *key, const char *value) {
37  char out[72];
38  snprintf(out, sizeof(out), "%s=%s\n", key, value);
39  btWrite(out);
40}
41
42void sendInt(const char *key, long value) {
43  char text[12];
44  snprintf(text, sizeof(text), "%ld", value);
45  sendText(key, text);
46}
47
48void sendFloat(const char *key, float value) {
49  char text[16];
50  dtostrf(value, 1, 1, text);
51  sendText(key, text);
52}
53
54void handleLine(char *text) {
55  char *eq = strchr(text, '=');
56  if (eq == nullptr) {
57    if (text[strlen(text) - 1] == '?') {
58      btWrite("@v=1.0\n");  // the "@v" line tells the app the code version
59      sendAll();
60    }
61    return;
62  }
63  *eq = '\0';
64  onValue(text, eq + 1);
65}
66
67void feed(char c) {
68  lastRxMs = millis();
69  if (c == '\n' || c == '\r') {
70    if (lineLen == 0) return;
71    line[lineLen] = '\0';
72    lineLen = 0;
73    handleLine(line);
74  } else if (lineLen < sizeof(line) - 1) {
75    line[lineLen++] = c;
76  }
77}
78
79// ── Bluetooth (Nordic UART) ──
80#define UART_SERVICE "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
81#define UART_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
82#define UART_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
83
84BLECharacteristic *txChar = nullptr;
85volatile bool linked = false;
86volatile bool linkLost = false;
87// incoming bytes move from the Bluetooth task to loop() through a small ring buffer
88const int RX_SIZE = 256;
89volatile uint8_t rxBuf[RX_SIZE];
90volatile int rxHead = 0, rxTail = 0;
91
92class ServerEvents : public BLEServerCallbacks {
93  void onConnect(BLEServer *server) override { linked = true; }
94  void onDisconnect(BLEServer *server) override { linked = false; linkLost = true; }
95};
96
97class RxEvents : public BLECharacteristicCallbacks {
98  void onWrite(BLECharacteristic *c) override {
99    auto v = c->getValue();
100    for (size_t i = 0; i < v.length(); i++) {
101      int next = (rxHead + 1) % RX_SIZE;
102      if (next == rxTail) break;
103      rxBuf[rxHead] = (uint8_t)v[i];
104      rxHead = next;
105    }
106  }
107};
108
109// lines go out in 20-byte packets (works with every phone)
110void btWrite(const char *text) {
111  if (!linked || txChar == nullptr) return;
112  size_t n = strlen(text);
113  for (size_t i = 0; i < n; i += 20) {
114    size_t len = n - i < 20 ? n - i : 20;
115    txChar->setValue((uint8_t *)text + i, len);
116    txChar->notify();
117    delay(4);
118  }
119}
120
121void btBegin() {
122  BLEDevice::init(BLE_NAME);
123  BLEServer *server = BLEDevice::createServer();
124  server->setCallbacks(new ServerEvents());
125  BLEService *uart = server->createService(UART_SERVICE);
126  txChar = uart->createCharacteristic(UART_TX, BLECharacteristic::PROPERTY_NOTIFY);
127  txChar->addDescriptor(new BLE2902());
128  BLECharacteristic *rx = uart->createCharacteristic(UART_RX, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR);
129  rx->setCallbacks(new RxEvents());
130  uart->start();
131  BLEAdvertisementData adv;
132  adv.setFlags(0x06);
133  adv.setCompleteServices(BLEUUID(UART_SERVICE));
134  BLEAdvertisementData scan;
135  scan.setName(BLE_NAME);
136  BLEAdvertising *advertising = BLEDevice::getAdvertising();
137  advertising->setAdvertisementData(adv);
138  advertising->setScanResponseData(scan);
139  BLEDevice::startAdvertising();
140}
141
142void btPoll() {
143  while (rxTail != rxHead) {
144    char c = (char)rxBuf[rxTail];
145    rxTail = (rxTail + 1) % RX_SIZE;
146    feed(c);
147  }
148  if (linkLost) {
149    linkLost = false;
150    onLinkLost();
151    delay(100);
152    BLEDevice::startAdvertising();
153  }
154}
155
156// ── ESP32 ──
157// if you only see boxes, turn the blue trimmer on the back (contrast)
158LiquidCrystal_I2C lcd(LCD_ADDRESS, LCD_COLS, LCD_ROWS);
159char rows[LCD_ROWS][LCD_COLS + 1];
160bool lightOn = true;
161
162// the LCD only knows basic Latin letters: accented ones are simplified (é → e), others become ?
163const char FOLD[] = "AAAAAAACEEEEIIIIDNOOOOOxOUUUUYPsaaaaaaaceeeeiiiidnooooo/ouuuuypyAaAaAaCcCcCcCcDdDdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIiJjJjKkkLlLlLlLlLlNnNnNnnNnOoOoOoOoRrRrRrSsSsSsSsTtTtTtUuUuUuUuUuUuWwYyYZzZzZzs";
164
165void toAscii(const char *in, char *out, size_t size) {
166  size_t n = 0;
167  const unsigned char *p = (const unsigned char *)in;
168  while (*p && n + 1 < size) {
169    unsigned char c = *p;
170    if (c < 0x80) { out[n++] = c >= 32 ? c : ' '; p++; continue; }
171    int len = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : c >= 0xC0 ? 2 : 1;
172    unsigned int code = (len == 2 && p[1]) ? ((c & 0x1F) << 6) | (p[1] & 0x3F) : 0;
173    out[n++] = (code >= 0xC0 && code <= 0x17F) ? FOLD[code - 0xC0] : '?';
174    for (int k = 0; k < len && *p; k++) p++;
175  }
176  out[n] = '\0';
177}
178
179void showRows() {
180  for (int r = 0; r < LCD_ROWS; r++) {
181    lcd.setCursor(0, r);
182    bool ended = false;
183    for (int c = 0; c < LCD_COLS; c++) {
184      if (rows[r][c] == '\0') ended = true;
185      lcd.write(ended ? ' ' : rows[r][c]);
186    }
187  }
188}
189
190// "yazi=" flows the text over the rows, "satir1=" … replaces a single row
191void setText(const char *text) {
192  char flat[LCD_COLS * LCD_ROWS + 1];
193  toAscii(text, flat, sizeof(flat));
194  int len = strlen(flat);
195  for (int r = 0; r < LCD_ROWS; r++) {
196    int start = r * LCD_COLS;
197    int n = len > start ? min(LCD_COLS, len - start) : 0;
198    memcpy(rows[r], flat + start, n);
199    rows[r][n] = '\0';
200  }
201}
202
203void onValue(const char *key, const char *value) {
204  if (is(key, "yazi")) {
205    setText(value);
206    showRows();
207  } else if (strncmp(key, "satir", 5) == 0) {
208    int r = atoi(key + 5) - 1;
209    if (r < 0 || r >= LCD_ROWS) return;
210    toAscii(value, rows[r], LCD_COLS + 1);
211    showRows();
212  } else if (is(key, "isik")) {
213    lightOn = isOn(value);
214    if (lightOn) lcd.backlight(); else lcd.noBacklight();
215  }
216}
217
218void sendAll() {
219  char flat[LCD_COLS * LCD_ROWS + 1];
220  snprintf(flat, sizeof(flat), rows[1][0] ? "%-16s%s" : "%s", rows[0], rows[1]);
221  if (flat[0]) sendText("yazi", flat);
222  sendInt("isik", lightOn);
223}
224
225void onLinkLost() {
226}
227
228void setup() {
229  Serial.begin(115200);
230  Wire.begin(SDA_PIN, SCL_PIN);
231  lcd.init();
232  lcd.backlight();
233  setText("BlueGrays");
234  strncpy(rows[1], BLE_NAME, LCD_COLS);
235  rows[1][LCD_COLS] = '\0';
236  showRows();
237  btBegin();
238  Serial.print(F("BlueGrays Bluetooth: "));
239  Serial.println(BLE_NAME);
240}
241
242void loop() {
243  btPoll();
244}
245

FAQ

iPhone에서도 돼요?

네. ESP32의 내장 Bluetooth Low Energy(BLE)는 iPhone, Android와 모두 통신해요. iPhone은 HC-05나 HC-06 같은 클래식 Bluetooth 모듈에 연결할 수 없고, 이 프로젝트에는 그런 모듈이 필요 없어요. 휴대폰의 Bluetooth 설정에서 보드를 페어링하려고 하지 마세요. BLE 보드는 거기에 안 보일 수 있고, 그게 정상이에요. 연결은 BlueGrays 앱이 해요.

é, ü, ñ 같은 악센트 문자를 보여 줄 수 있어요?

악센트 문자 그대로는 안 돼요. 텍스트를 디스플레이로 보내기 전에 코드가 악센트가 붙은 라틴 문자를 기본 문자로 바꿔요. é는 e, ü는 u, ñ는 n, ç는 c가 돼요. café를 입력하면 디스플레이에 cafe가 나와서 글이 읽기 쉽게 남아요. 변환 표에 없는 문자(이모지, 한글, 키릴 문자, 일본어 문자, °와 € 같은 기호)는 물음표로 나와요. 패널의 LCD 미리 보기에서 보내기 전에 글이 어떻게 보일지 확인할 수 있어요.

20x4 LCD를 써도 돼요?

네. 마법사와 코드 화면에 LCD 종류 선택이 있어요: 16x2 또는 20x4. 20x4를 고르면 앱이 그 크기에 맞는 코드를 만들어요. 배선은 같아서 같은 핀에 전선 4가닥이에요. 16x2용으로 받은 코드에서 열과 행 숫자를 손으로 고치지 마세요. 코드의 다른 부분도 크기에 따라 달라지거든요. 올바른 방법은 앱에서 LCD 종류를 바꾸고 코드를 다시 받는 거예요. 이 가이드는 16x2 디스플레이로 만들었어요.

몇 글자까지 들어가고, 긴 글은 흘러가요?

16x2 디스플레이에는 32글자가 들어가요. 16글자씩 두 줄이에요. 패널의 입력 칸은 그보다 많이 받지 않아요. 처음 16글자는 위쪽 줄에, 나머지는 아래쪽 줄에 가요. 코드는 단어를 보지 않기 때문에 줄 끝에서 단어가 둘로 잘릴 수 있어요. 글은 흐르지 않고 그 자리에 머물러요. 단어를 아래쪽 줄로 내리려면 앞에 공백을 넣으세요. 보내기 전에 LCD 미리 보기에서 나뉜 모습을 볼 수 있어요. 새 글은 이전 글을 대신해요.