ES-112Iniciante

ESP32 Bluetooth: texto no LCD

Escreva uma mensagem no celular e ela aparece por Bluetooth em um LCD 16x2, sem internet nem Wi-Fi. Este projeto é o guia passo a passo do modelo Bluetooth Texto no LCD do app, montado com um ESP32 e um LCD I2C. Vá em Minha oficina › Dispositivos › Adicionar dispositivo › Bluetooth, escolha Texto no LCD e grave o código com Pegar o código. O botão Configurar como painel Bluetooth nesta página também abre o assistente com este modelo.

0.0(0)
ESP32 Bluetooth: texto no LCD
Escreva uma mensagem no celular, toque em Enviar e ela aparece no LCD na sua mesa, sem internet nem servidor. O ESP32 já tem Bluetooth, então o celular se conecta direto à placa, e com o módulo I2C a tela só precisa de quatro fios. Em um LCD 16x2 cabem 32 caracteres: 16 em cima, o resto embaixo. O código troca letras acentuadas como ã, ç e é por letras simples e coloca um ponto de interrogação no lugar dos caracteres desconhecidos. O interruptor Luz de fundo do painel liga e desliga a luz. No app, escolha o modelo Texto no LCD, grave o código e encontre sua placa na lista. Você aprende: enviar texto por Bluetooth Low Energy, usar um LCD I2C, dividir o texto em linhas e converter letras com uma tabela.

Vídeo

Esquema do circuito

ESP32 Bluetooth: texto no LCD - Esquema do circuito

Código-fonte

C++ (Arduino IDE)
1// ┌───────────────────────────┐
2// │ BlueGrays · bluegrays.com │
3// │ Bluetooth · ESP32         │
4// │ BG-Ekran                  │
5// └───────────────────────────┘
6// Texto no LCD
7// Placa no Arduino IDE: ESP32 Dev Module
8// a biblioteca BLE vem com o pacote de placas ESP32, não precisa instalar nada a mais
9
10#include <BLEDevice.h>
11#include <BLEServer.h>
12#include <BLE2902.h>
13#include <Wire.h>
14#include <LiquidCrystal_I2C.h>  // Gerenciador de bibliotecas: 'LiquidCrystal I2C' (Frank de Brabander)
15
16const char BLE_NAME[] = "BG-Ekran";  // a placa se anuncia com este nome e o app a encontra assim na lista
17
18// Pinos: mude aqui se você ligou de outro jeito
19const int SDA_PIN = 21, SCL_PIN = 22;
20const int LCD_COLS = 16, LCD_ROWS = 2;  // tamanho do LCD: colunas × linhas
21const uint8_t LCD_ADDRESS = 0x27;  // a maioria dos LCD I2C usa 0x27; se a tela ficar vazia, tente 0x3F
22
23void btWrite(const char *text);
24void onValue(const char *key, const char *value);
25void sendAll();
26void onLinkLost();
27
28// ── O app envia linhas "chave=valor"; ao receber "?" a placa manda todos os valores ──
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");  // a linha "@v" informa ao app a versão do código
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// os bytes recebidos passam da tarefa Bluetooth para o loop() por um pequeno buffer circular
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// as linhas saem em pacotes de 20 bytes (funciona com qualquer celular)
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// se aparecerem só quadradinhos, gire o trimpot azul atrás (contraste)
158LiquidCrystal_I2C lcd(LCD_ADDRESS, LCD_COLS, LCD_ROWS);
159char rows[LCD_ROWS][LCD_COLS + 1];
160bool lightOn = true;
161
162// o LCD só conhece letras latinas básicas: os acentos somem (é → e) e as outras viram ?
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=" distribui o texto pelas linhas, "satir1=" … troca uma só linha
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

Perguntas frequentes

Funciona com iPhone?

Funciona. O Bluetooth Low Energy (BLE) embutido no ESP32 conversa com iPhone e com Android. O iPhone não se conecta a módulos de Bluetooth clássico como o HC-05 e o HC-06, e este projeto não precisa deles. Não tente parear a placa nas configurações de Bluetooth do celular; placas BLE podem não aparecer lá, isso é normal. Quem faz a conexão é o app BlueGrays.

Os acentos aparecem na tela?

Não como acentos. Antes de mandar o texto para a tela, o código troca as letras acentuadas por letras simples: ã vira a, ç vira c, é vira e, õ vira o. Se você escrever Coração, a tela mostra Coracao; o texto continua legível. Os caracteres que não estão na tabela de conversão (emojis, letras cirílicas ou japonesas, símbolos como ° e €, aspas curvas de alguns teclados) aparecem como ponto de interrogação. A Prévia do LCD no painel mostra como o texto vai ficar antes de enviar.

Posso usar um LCD 20x4?

Pode. O assistente e a tela do código têm a opção Tipo de LCD: 16x2 ou 20x4. Se você escolher 20x4, o app gera o código para esse tamanho. A ligação é a mesma: quatro fios nos mesmos pinos. Não mude à mão o número de colunas e linhas em um código que você pegou para 16x2, porque outras partes do código também dependem do tamanho. O caminho certo é trocar o tipo de LCD no app e pegar o código de novo. Este guia foi montado com uma tela 16x2.

Quantos caracteres cabem? O texto longo rola na tela?

Em um LCD 16x2 cabem 32 caracteres: duas linhas de 16. O campo de texto do painel também não aceita mais que isso. Os 16 primeiros caracteres vão para a linha de cima e o resto para a de baixo; o código não olha para as palavras, então uma palavra pode ficar cortada no fim da linha. O texto não rola, fica parado. Para empurrar uma palavra para a linha de baixo, coloque espaços antes dela; a Prévia do LCD mostra a divisão antes de enviar. Um texto novo substitui o anterior.