Exemplo Bluetooth Chat com ESP32 - Tutorial de Interface de Mensagens Bidirecional
Visão Geral
O exemplo Bluetooth Chat permite a troca de mensagens de texto bidirecional entre o seu ESP32 e um smartphone por meio do app DIYables Bluetooth STEM. Projetado para placas ESP32, com suporte a conexões BLE (Bluetooth Low Energy) e Bluetooth Clássico. Envie e receba mensagens de texto em tempo real, implemente o tratamento de comandos personalizados e faça uma ponte entre o Serial Monitor e o Bluetooth — perfeito para depuração, controle remoto e projetos interativos.
Este exemplo suporta dois modos Bluetooth:
ESP32 BLE (Bluetooth Low Energy): Funciona no Android e no iOS
ESP32 Bluetooth Clássico: Funciona somente no Android. O iOS não suporta o Bluetooth Clássico. Use o BLE se você precisar de suporte ao iOS.
Recursos
Mensagens Bidirecionais: Envie e receba mensagens de texto em tempo real
Modo Eco: Devolve automaticamente ao app as mensagens recebidas
Tratamento de Comandos: Processe comandos de texto personalizados (ping, status, time, heap)
Mensagens Periódicas: Envie atualizações automáticas de status em intervalos configuráveis
Ponte Serial-Bluetooth: Digite mensagens no Serial Monitor e envie-as para o app
BLE e Bluetooth Clássico: Escolha o modo Bluetooth que melhor atende ao seu projeto
Multiplataforma: O modo BLE funciona no Android e no iOS; o Bluetooth Clássico funciona no Android
Opção de Baixo Consumo: O modo BLE consome menos energia que o Bluetooth Clássico
Divulgação: Alguns dos links desta seção são links de afiliado da Amazon. Podemos receber uma comissão pelas compras feitas por meio desses links, sem custo adicional para você. Agradecemos o seu apoio.
Conecte a placa ESP32 ao seu computador usando um cabo USB.
Abra o Arduino IDE no seu computador.
Selecione a placa ESP32 apropriada e a porta COM.
Navegue até o ícone Libraries na barra esquerda do Arduino IDE.
Pesquise "DIYables Bluetooth" e encontre a biblioteca DIYables Bluetooth da DIYables
Clique no botão Install para instalar a biblioteca.
Você será solicitado a instalar algumas outras dependências da biblioteca
Clique no botão Install All para instalar todas as dependências da biblioteca.
Escolha um dos dois modos Bluetooth abaixo, de acordo com a sua necessidade:
Código do ESP32 para Bluetooth Clássico (funciona com o app somente no Android)
Observação: O Bluetooth Clássico NÃO é suportado no iOS. Se você precisa de suporte ao iOS, use o código BLE abaixo.
No Arduino IDE, vá em File Examples DIYables Bluetooth Esp32Bluetooth_Chat, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - ESP32 Classic Bluetooth Chat Example * Works with DIYables Bluetooth STEM app on Android * Note: Classic Bluetooth is NOT supported on iOS. Use BLE examples for iOS support. * * This example demonstrates the Bluetooth Chat feature: * - Two-way text messaging via Bluetooth * - Receive messages from mobile app * - Send messages to mobile app * * Compatible Boards: * - ESP32 (all variants with Classic Bluetooth) * - ESP32-WROOM-32 * - ESP32-DevKitC * - ESP32-WROVER * * Note: Select "Huge APP (3MB No OTA/1MB SPIFFS)" partition scheme * in Arduino IDE: Tools > Partition Scheme * * Setup: * 1. Upload the sketch to your ESP32 * 2. Open Serial Monitor (115200 baud) to see connection status and messages * 3. Use DIYables Bluetooth App to connect and chat * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */#include <DIYables_BluetoothServer.h>#include <DIYables_BluetoothChat.h>#include <platforms/DIYables_Esp32Bluetooth.h>// Create Bluetooth instancesDIYables_Esp32Bluetooth bluetooth("ESP32_Chat");DIYables_BluetoothServer bluetoothServer(bluetooth);// Create Chat app instanceDIYables_BluetoothChat bluetoothChat;// Variables for periodic messagesunsignedlong lastMessageTime = 0;constunsignedlong MESSAGE_INTERVAL = 10000; // Send message every 10 secondsint messageCount = 0;voidsetup() {Serial.begin(115200);delay(1000);Serial.println("DIYables Bluetooth - ESP32 Chat Example");// Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin();// Add chat app to server bluetoothServer.addApp(&bluetoothChat);// Set up connection event callbacks bluetoothServer.setOnConnected([]() {Serial.println("Bluetooth connected!"); bluetoothChat.send("Hello! ESP32 is ready to chat."); }); bluetoothServer.setOnDisconnected([]() {Serial.println("Bluetooth disconnected!"); messageCount = 0; });// Set up callback for received chat messages bluetoothChat.onChatMessage([](const String& message) {Serial.print("Received: ");Serial.println(message);// Echo the message backString response = "Echo: "; response += message; bluetoothChat.send(response);// You can add custom command handling hereif (message.equalsIgnoreCase("ping")) { bluetoothChat.send("pong!"); } elseif (message.equalsIgnoreCase("status")) { bluetoothChat.send("ESP32 is running normally"); } elseif (message.equalsIgnoreCase("time")) {String timeMsg = "Uptime: "; timeMsg += String(millis() / 1000); timeMsg += " seconds"; bluetoothChat.send(timeMsg); } elseif (message.equalsIgnoreCase("heap")) {String heapMsg = "Free heap: "; heapMsg += String(ESP.getFreeHeap()); heapMsg += " bytes"; bluetoothChat.send(heapMsg); } });Serial.println("Waiting for Bluetooth connection..."); Serial.println("Type 'ping', 'status', 'time', or'heap' in the app to test commands");}void loop() {// Handle Bluetooth server communications bluetoothServer.loop();// Send periodic status message (only when connected)if (bluetooth.isConnected() && millis() - lastMessageTime >= MESSAGE_INTERVAL) { lastMessageTime = millis(); messageCount++;String statusMsg = "Status update #"; statusMsg += String(messageCount); statusMsg += " - All systems operational"; bluetoothChat.send(statusMsg);Serial.print("Sent: ");Serial.println(statusMsg); }// Optional: Read from Serial and send to Bluetoothif (Serial.available()) {String serialMsg = Serial.readStringUntil('\n'); serialMsg.trim();if (serialMsg.length() > 0 && bluetooth.isConnected()) { bluetoothChat.send(serialMsg);Serial.print("Sent from Serial: ");Serial.println(serialMsg); } }delay(10);}
Clique no botão Upload no Arduino IDE para fazer o upload do código para o ESP32
Abra o Serial Monitor
Veja o resultado no Serial Monitor. Ele deve ser parecido com o abaixo:
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
DIYables Bluetooth - ESP32 Chat Example
Waiting for Bluetooth connection...
Type 'ping', 'status', 'time', or 'heap' in the app to test commands
Ln 11, Col 1
ESP32 Dev Module on COM15
2
Código do ESP32 para BLE (funciona com o app no Android e no iOS)
No Arduino IDE, vá em File Examples DIYables Bluetooth Esp32BLE_Chat, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - ESP32 BLE Chat Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Chat feature: * - Two-way text messaging via Bluetooth * - Receive messages from mobile app * - Send messages to mobile app * * Compatible Boards: * - ESP32-WROOM-32 * - ESP32-DevKitC * - ESP32-WROVER * - ESP32-S3 * - ESP32-C3 * - Any ESP32 board supporting BLE * * Note: Select "Huge APP (3MB No OTA/1MB SPIFFS)" partition scheme * in Arduino IDE: Tools > Partition Scheme * * Setup: * 1. Upload the sketch to your ESP32 * 2. Open Serial Monitor (115200 baud) to see connection status and messages * 3. Use DIYables Bluetooth App to connect and chat * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */#include <DIYables_BluetoothServer.h>#include <DIYables_BluetoothChat.h>#include <platforms/DIYables_Esp32BLE.h>// BLE Configurationconst char* DEVICE_NAME = "ESP32BLE_Chat";const char* SERVICE_UUID = "19B10000-E8F2-537E-4F6C-D104768A1214";const char* TX_UUID = "19B10001-E8F2-537E-4F6C-D104768A1214";const char* RX_UUID = "19B10002-E8F2-537E-4F6C-D104768A1214";// Create Bluetooth instancesDIYables_Esp32BLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID);DIYables_BluetoothServer bluetoothServer(bluetooth);// Create Chat app instanceDIYables_BluetoothChat bluetoothChat;// Variables for periodic messagesunsignedlong lastMessageTime = 0;constunsignedlong MESSAGE_INTERVAL = 10000; // Send message every 10 secondsint messageCount = 0;voidsetup() {Serial.begin(115200);delay(1000);Serial.println("DIYables Bluetooth - ESP32 BLE Chat Example");// Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin();// Add chat app to server bluetoothServer.addApp(&bluetoothChat);// Set up connection event callbacks bluetoothServer.setOnConnected([]() {Serial.println("Bluetooth connected!"); bluetoothChat.send("Hello! ESP32 BLE is ready to chat."); }); bluetoothServer.setOnDisconnected([]() {Serial.println("Bluetooth disconnected!"); messageCount = 0; });// Set up callback for received chat messages bluetoothChat.onChatMessage([](const String& message) {Serial.print("Received: ");Serial.println(message);// Echo the message backString response = "Echo: "; response += message; bluetoothChat.send(response);// Custom command handlingif (message.equalsIgnoreCase("ping")) { bluetoothChat.send("pong!"); } elseif (message.equalsIgnoreCase("status")) { bluetoothChat.send("ESP32 BLE is running normally"); } elseif (message.equalsIgnoreCase("time")) {String timeMsg = "Uptime: "; timeMsg += String(millis() / 1000); timeMsg += " seconds"; bluetoothChat.send(timeMsg); } elseif (message.equalsIgnoreCase("heap")) {String heapMsg = "Free heap: "; heapMsg += String(ESP.getFreeHeap()); heapMsg += " bytes"; bluetoothChat.send(heapMsg); } });Serial.println("Waiting for Bluetooth connection..."); Serial.println("Type 'ping', 'status', 'time', or'heap' in the app to test commands");}void loop() { bluetoothServer.loop(); if (bluetooth.isConnected() && millis() - lastMessageTime >= MESSAGE_INTERVAL) { lastMessageTime = millis(); messageCount++; String statusMsg = "Status update #"; statusMsg += String(messageCount); statusMsg += " - All systems operational"; bluetoothChat.send(statusMsg); Serial.print("Sent: "); Serial.println(statusMsg); } if (Serial.available()) { String serialMsg = Serial.readStringUntil('\n'); serialMsg.trim();if (serialMsg.length() > 0 && bluetooth.isConnected()) { bluetoothChat.send(serialMsg);Serial.print("Sent from Serial: ");Serial.println(serialMsg); } }delay(10);}
Clique no botão Upload no Arduino IDE para fazer o upload do código para o ESP32
Abra o Serial Monitor
Veja o resultado no Serial Monitor. Ele deve ser parecido com o abaixo:
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
DIYables Bluetooth - ESP32 BLE Chat Example
Waiting for Bluetooth connection...
Type 'ping', 'status', 'time', or 'heap' in the app to test commands
Ln 11, Col 1
ESP32 Dev Module on COM15
2
App para Celular
Instale o DIYables Bluetooth App no seu smartphone: Android | iOS
Se você estiver usando o código do ESP32 para Bluetooth Clássico, você precisa parear o ESP32 com o seu celular Android antes de abrir o app:
Vá em Settings > Bluetooth no seu celular
Certifique-se de que o Bluetooth está ativado
Seu celular vai buscar os dispositivos disponíveis
Encontre e toque em "ESP32_Chat" na lista de dispositivos disponíveis
Confirme a solicitação de pareamento (não é necessário PIN)
Aguarde até aparecer "Paired" abaixo do nome do dispositivo
Se você estiver usando o código do ESP32 para BLE, não é necessário parear. Basta ir para a próxima etapa.
Abra o DIYables Bluetooth App
Ao abrir o app pela primeira vez, ele vai pedir permissões. Conceda as seguintes:
Permissão de Dispositivos Próximos (Android 12+) / permissão de Bluetooth (iOS) - necessária para buscar e conectar a dispositivos Bluetooth
Permissão de Localização (somente Android 11 e anteriores) - exigida pelas versões mais antigas do Android para buscar dispositivos BLE
Certifique-se de que o Bluetooth está ativado no seu celular
Na tela inicial, toque no botão Connect. O app vai buscar dispositivos BLE e Bluetooth Clássico.
Encontre e toque no seu dispositivo nos resultados da busca para conectar:
Para o Bluetooth Clássico: toque em "ESP32_Chat"
Para o BLE: toque em "ESP32BLE_Chat"
Depois de conectado, o app volta automaticamente para a tela inicial. Selecione o app Chat no menu de apps.
Observação: Você pode tocar no ícone de configurações na tela inicial para ocultar/mostrar apps na tela inicial. Para mais detalhes, veja o Manual do Usuário do DIYables Bluetooth App.
Digite uma mensagem no campo de texto e toque em Enviar
Agora volte ao Serial Monitor no Arduino IDE. Você verá:
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
Bluetooth connected!
Received: Hello
Received: ping
Received: status
Sent: Status update #1 - All systems operational
Ln 11, Col 1
ESP32 Dev Module on COM15
2
Digite mensagens no app e observe o feedback em tempo real no Serial Monitor
Experimente os comandos integrados: ping, status, time, heap
Você também pode digitar mensagens no Serial Monitor e elas serão enviadas ao app
Personalização Criativa - Adapte o Código ao Seu Projeto
Receber Mensagens do App
Use o callback onChatMessage() para tratar as mensagens recebidas do app. Você pode definir qualquer palavra de comando personalizada que faça sentido para o seu projeto — o ESP32 vai reagir de acordo:
Você pode adicionar quantos comandos personalizados precisar, incluindo mais blocos elseif. Por exemplo, adicione RELAY_ON / RELAY_OFF para controlar um relé, ou READ para disparar uma leitura de sensor — qualquer palavra que você digitar no app se torna um comando.
Enviar Mensagens ao App
Você pode enviar mensagens de texto do ESP32 para o app a qualquer momento:
// Send a simple text messagebluetoothChat.send("Hello from ESP32!");// Send sensor data as textfloat temperature = 25.3;bluetoothChat.send("Temperature: " + String(temperature) + "°C");// Send status updatesbluetoothChat.send("System ready");
Tratar Eventos de Conexão
Você pode detectar quando o app se conecta ou se desconecta do ESP32:
// Called when the app connects to ESP32bluetoothServer.setOnConnected([]() {Serial.println("Bluetooth connected!"); bluetoothChat.send("Welcome! ESP32 is ready to chat.");});// Called when the app disconnects from ESP32bluetoothServer.setOnDisconnected([]() {Serial.println("Bluetooth disconnected!");});// Check connection status anywhere in your codeif (bluetoothServer.isConnected()) { bluetoothChat.send("Still connected!");}
Ponte Serial-Bluetooth
Encaminhe para o app Bluetooth as mensagens digitadas no Serial Monitor do Arduino IDE:
voidloop() { bluetoothServer.loop();// Read from Serial and send to Bluetoothif (Serial.available()) {String serialMsg = Serial.readStringUntil('\n'); serialMsg.trim();if (serialMsg.length() > 0 && bluetooth.isConnected()) { bluetoothChat.send(serialMsg);Serial.print("Sent from Serial: ");Serial.println(serialMsg); } }delay(10);}
Como Usar o Chat
Controles da Interface do App
A interface de chat do DIYables Bluetooth App oferece:
Lista de Mensagens: Lista rolável que mostra as mensagens enviadas e recebidas
Campo de Texto: Digite sua mensagem na parte inferior
Botão Enviar: Toque para enviar a mensagem digitada
Rolagem Automática: Rola automaticamente até a mensagem mais recente
Comandos Integrados
O código de exemplo inclui estes comandos integrados:
ping ? Responde com "pong!"
status ? Informa o status de execução do ESP32
time ? Mostra o tempo de atividade em segundos
heap ? Mostra a memória heap livre em bytes
Exemplos de Programação
Chat Eco Básico
voidsetup() {// Set up chat callback bluetoothChat.onChatMessage([](const String& message) {Serial.print("Received: ");Serial.println(message);// Echo the message back bluetoothChat.send("Echo: " + message); });}
Controle de LED por Comandos
constint LED_PIN = 2; // Built-in LEDconstint RED_PIN = 16;constint GREEN_PIN = 17;constint BLUE_PIN = 18;voidsetup() {pinMode(LED_PIN, OUTPUT);pinMode(RED_PIN, OUTPUT);pinMode(GREEN_PIN, OUTPUT);pinMode(BLUE_PIN, OUTPUT); bluetoothChat.onChatMessage([](constString& message) {String cmd = message; cmd.toUpperCase();if (cmd == "LED ON") {digitalWrite(LED_PIN, HIGH); bluetoothChat.send("LED is now ON"); } elseif (cmd == "LED OFF") {digitalWrite(LED_PIN, LOW); bluetoothChat.send("LED is now OFF"); } elseif (cmd == "RED") {digitalWrite(RED_PIN, HIGH);digitalWrite(GREEN_PIN, LOW);digitalWrite(BLUE_PIN, LOW); bluetoothChat.send("Red LED activated"); } elseif (cmd == "GREEN") {digitalWrite(RED_PIN, LOW);digitalWrite(GREEN_PIN, HIGH);digitalWrite(BLUE_PIN, LOW); bluetoothChat.send("Green LED activated"); } elseif (cmd == "BLUE") {digitalWrite(RED_PIN, LOW);digitalWrite(GREEN_PIN, LOW);digitalWrite(BLUE_PIN, HIGH); bluetoothChat.send("Blue LED activated"); } elseif (cmd == "OFF") {digitalWrite(RED_PIN, LOW);digitalWrite(GREEN_PIN, LOW);digitalWrite(BLUE_PIN, LOW); bluetoothChat.send("All LEDs off"); } elseif (cmd == "HELP") { bluetoothChat.send("Commands: LED ON, LED OFF, RED, GREEN, BLUE, OFF, HELP"); } else { bluetoothChat.send("Unknown command. Type HELP for list."); } });}
Fique à vontade para compartilhar o link deste tutorial. Porém, por favor, não use nosso conteúdo em outros sites. Investimos muito esforço e tempo para criar este conteúdo, por favor respeite nosso trabalho!