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.
Exemplo Bluetooth Chat com ESP32 - Tutorial de Interface de Mensagens Bidirecional

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

Código do ESP32

Passos Rápidos

Siga estas instruções passo a passo:

  • Se esta é a primeira vez que você usa o ESP32, consulte o tutorial sobre como configurar o ambiente para ESP32 no Arduino IDE.
  • 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.
Biblioteca DIYables Bluetooth para ESP32
  • 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.
Dependência do DIYables Bluetooth para ESP32

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 instances DIYables_Esp32Bluetooth bluetooth("ESP32_Chat"); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Chat app instance DIYables_BluetoothChat bluetoothChat; // Variables for periodic messages unsigned long lastMessageTime = 0; const unsigned long MESSAGE_INTERVAL = 10000; // Send message every 10 seconds int messageCount = 0; void setup() { 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 back String response = "Echo: "; response += message; bluetoothChat.send(response); // You can add custom command handling here if (message.equalsIgnoreCase("ping")) { bluetoothChat.send("pong!"); } else if (message.equalsIgnoreCase("status")) { bluetoothChat.send("ESP32 is running normally"); } else if (message.equalsIgnoreCase("time")) { String timeMsg = "Uptime: "; timeMsg += String(millis() / 1000); timeMsg += " seconds"; bluetoothChat.send(timeMsg); } else if (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 Bluetooth 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
···
8 Serial.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 Configuration const 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 instances DIYables_Esp32BLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Chat app instance DIYables_BluetoothChat bluetoothChat; // Variables for periodic messages unsigned long lastMessageTime = 0; const unsigned long MESSAGE_INTERVAL = 10000; // Send message every 10 seconds int messageCount = 0; void setup() { 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 back String response = "Echo: "; response += message; bluetoothChat.send(response); // Custom command handling if (message.equalsIgnoreCase("ping")) { bluetoothChat.send("pong!"); } else if (message.equalsIgnoreCase("status")) { bluetoothChat.send("ESP32 BLE is running normally"); } else if (message.equalsIgnoreCase("time")) { String timeMsg = "Uptime: "; timeMsg += String(millis() / 1000); timeMsg += " seconds"; bluetoothChat.send(timeMsg); } else if (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
···
8 Serial.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.
DIYables Bluetooth App - Tela Inicial com o Botão de Busca
  • 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.
DIYables Bluetooth App - Tela Inicial com o App Chat

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
DIYables Bluetooth App - Tela do Chat

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
···
8 Serial.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:

bluetoothChat.onChatMessage([](const String& message) { Serial.print("Received: "); Serial.println(message); // Process the message if (message == "LED_ON") { digitalWrite(2, HIGH); bluetoothChat.send("LED turned ON"); } else if (message == "LED_OFF") { digitalWrite(2, LOW); bluetoothChat.send("LED turned OFF"); } else { bluetoothChat.send("Unknown command: " + message); } });

Você pode adicionar quantos comandos personalizados precisar, incluindo mais blocos else if. 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 message bluetoothChat.send("Hello from ESP32!"); // Send sensor data as text float temperature = 25.3; bluetoothChat.send("Temperature: " + String(temperature) + "°C"); // Send status updates bluetoothChat.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 ESP32 bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); bluetoothChat.send("Welcome! ESP32 is ready to chat."); }); // Called when the app disconnects from ESP32 bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Check connection status anywhere in your code if (bluetoothServer.isConnected()) { bluetoothChat.send("Still connected!"); }

Ponte Serial-Bluetooth

Encaminhe para o app Bluetooth as mensagens digitadas no Serial Monitor do Arduino IDE:

void loop() { bluetoothServer.loop(); // Read from Serial and send to Bluetooth 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); }

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

void setup() { // 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

const int LED_PIN = 2; // Built-in LED const int RED_PIN = 16; const int GREEN_PIN = 17; const int BLUE_PIN = 18; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); bluetoothChat.onChatMessage([](const String& message) { String cmd = message; cmd.toUpperCase(); if (cmd == "LED ON") { digitalWrite(LED_PIN, HIGH); bluetoothChat.send("LED is now ON"); } else if (cmd == "LED OFF") { digitalWrite(LED_PIN, LOW); bluetoothChat.send("LED is now OFF"); } else if (cmd == "RED") { digitalWrite(RED_PIN, HIGH); digitalWrite(GREEN_PIN, LOW); digitalWrite(BLUE_PIN, LOW); bluetoothChat.send("Red LED activated"); } else if (cmd == "GREEN") { digitalWrite(RED_PIN, LOW); digitalWrite(GREEN_PIN, HIGH); digitalWrite(BLUE_PIN, LOW); bluetoothChat.send("Green LED activated"); } else if (cmd == "BLUE") { digitalWrite(RED_PIN, LOW); digitalWrite(GREEN_PIN, LOW); digitalWrite(BLUE_PIN, HIGH); bluetoothChat.send("Blue LED activated"); } else if (cmd == "OFF") { digitalWrite(RED_PIN, LOW); digitalWrite(GREEN_PIN, LOW); digitalWrite(BLUE_PIN, LOW); bluetoothChat.send("All LEDs off"); } else if (cmd == "HELP") { bluetoothChat.send("Commands: LED ON, LED OFF, RED, GREEN, BLUE, OFF, HELP"); } else { bluetoothChat.send("Unknown command. Type HELP for list."); } }); }

Sistema de Consulta de Sensores

#include <DHT.h> DHT dht(4, DHT22); void setup() { dht.begin(); bluetoothChat.onChatMessage([](const String& message) { String cmd = message; cmd.toUpperCase(); if (cmd == "TEMP") { float temp = dht.readTemperature(); if (!isnan(temp)) { bluetoothChat.send("Temperature: " + String(temp, 1) + " °C"); } else { bluetoothChat.send("Error reading temperature sensor"); } } else if (cmd == "HUMIDITY") { float hum = dht.readHumidity(); if (!isnan(hum)) { bluetoothChat.send("Humidity: " + String(hum, 1) + " %"); } else { bluetoothChat.send("Error reading humidity sensor"); } } else if (cmd == "ALL") { float temp = dht.readTemperature(); float hum = dht.readHumidity(); bluetoothChat.send("Temp: " + String(temp, 1) + "°C | Humidity: " + String(hum, 1) + "%"); } else if (cmd == "HELP") { bluetoothChat.send("Commands: TEMP, HUMIDITY, ALL, HELP"); } }); }

Controle de Relé com Confirmação

const int RELAY_1 = 16; const int RELAY_2 = 17; bool relay1State = false; bool relay2State = false; void setup() { pinMode(RELAY_1, OUTPUT); pinMode(RELAY_2, OUTPUT); digitalWrite(RELAY_1, LOW); digitalWrite(RELAY_2, LOW); bluetoothChat.onChatMessage([](const String& message) { String cmd = message; cmd.toUpperCase(); if (cmd == "R1 ON") { digitalWrite(RELAY_1, HIGH); relay1State = true; bluetoothChat.send("Relay 1: ON"); } else if (cmd == "R1 OFF") { digitalWrite(RELAY_1, LOW); relay1State = false; bluetoothChat.send("Relay 1: OFF"); } else if (cmd == "R2 ON") { digitalWrite(RELAY_2, HIGH); relay2State = true; bluetoothChat.send("Relay 2: ON"); } else if (cmd == "R2 OFF") { digitalWrite(RELAY_2, LOW); relay2State = false; bluetoothChat.send("Relay 2: OFF"); } else if (cmd == "STATUS") { bluetoothChat.send("Relay 1: " + String(relay1State ? "ON" : "OFF")); bluetoothChat.send("Relay 2: " + String(relay2State ? "ON" : "OFF")); } else if (cmd == "HELP") { bluetoothChat.send("Commands: R1 ON, R1 OFF, R2 ON, R2 OFF, STATUS, HELP"); } }); }

Técnicas Avançadas de Programação

Atualizações Periódicas de Status

unsigned long lastMessageTime = 0; const unsigned long MESSAGE_INTERVAL = 10000; // 10 seconds void loop() { bluetoothServer.loop(); // Send periodic status updates (only when connected) if (bluetooth.isConnected() && millis() - lastMessageTime >= MESSAGE_INTERVAL) { lastMessageTime = millis(); messageCount++; String statusMsg = "Status update #" + String(messageCount); statusMsg += " - Uptime: " + String(millis() / 1000) + "s"; statusMsg += " - Heap: " + String(ESP.getFreeHeap()) + " bytes"; bluetoothChat.send(statusMsg); } delay(10); }

Registro de Mensagens

// Log all messages to Serial with timestamps bluetoothChat.onChatMessage([](const String& message) { unsigned long timestamp = millis() / 1000; Serial.print("["); Serial.print(timestamp); Serial.print("s] Received: "); Serial.println(message); // Process and respond String response = processCommand(message); bluetoothChat.send(response); Serial.print("["); Serial.print(millis() / 1000); Serial.print("s] Sent: "); Serial.println(response); }); String processCommand(const String& cmd) { if (cmd.equalsIgnoreCase("ping")) return "pong!"; if (cmd.equalsIgnoreCase("status")) return "All systems operational"; if (cmd.equalsIgnoreCase("time")) return "Uptime: " + String(millis() / 1000) + "s"; return "Echo: " + cmd; }

Analisador de Comandos com Argumentos

bluetoothChat.onChatMessage([](const String& message) { // Parse command and argument (format: "COMMAND ARG") int spaceIndex = message.indexOf(' '); String command, argument; if (spaceIndex > 0) { command = message.substring(0, spaceIndex); argument = message.substring(spaceIndex + 1); } else { command = message; argument = ""; } command.toUpperCase(); if (command == "PWM") { int value = argument.toInt(); value = constrain(value, 0, 255); analogWrite(16, value); bluetoothChat.send("PWM set to " + String(value)); } else if (command == "DELAY") { int ms = argument.toInt(); bluetoothChat.send("Waiting " + String(ms) + "ms..."); delay(ms); bluetoothChat.send("Done!"); } else if (command == "PIN") { // Format: "PIN 13 HIGH" or "PIN 13 LOW" int secondSpace = argument.indexOf(' '); if (secondSpace > 0) { int pin = argument.substring(0, secondSpace).toInt(); String state = argument.substring(secondSpace + 1); state.toUpperCase(); digitalWrite(pin, state == "HIGH" ? HIGH : LOW); bluetoothChat.send("Pin " + String(pin) + " set " + state); } } });

Exemplos de Integração com Hardware

Controle de Servo pelo Chat

#include <ESP32Servo.h> Servo myServo; const int SERVO_PIN = 13; void setup() { myServo.attach(SERVO_PIN); bluetoothChat.onChatMessage([](const String& message) { // Accept angle commands like "90" or "SERVO 90" String cmd = message; cmd.toUpperCase(); int angle = -1; if (cmd.startsWith("SERVO ")) { angle = cmd.substring(6).toInt(); } else { angle = cmd.toInt(); if (angle == 0 && cmd != "0") angle = -1; // Not a number } if (angle >= 0 && angle <= 180) { myServo.write(angle); bluetoothChat.send("Servo moved to " + String(angle) + "°"); } else if (cmd == "SWEEP") { bluetoothChat.send("Sweeping servo..."); for (int a = 0; a <= 180; a += 5) { myServo.write(a); delay(30); } for (int a = 180; a >= 0; a -= 5) { myServo.write(a); delay(30); } bluetoothChat.send("Sweep complete"); } }); }

Controle de Motor pelo Chat

const int MOTOR_PWM = 16; const int MOTOR_DIR1 = 18; const int MOTOR_DIR2 = 19; void setup() { pinMode(MOTOR_PWM, OUTPUT); pinMode(MOTOR_DIR1, OUTPUT); pinMode(MOTOR_DIR2, OUTPUT); bluetoothChat.onChatMessage([](const String& message) { String cmd = message; cmd.toUpperCase(); if (cmd == "FORWARD") { digitalWrite(MOTOR_DIR1, HIGH); digitalWrite(MOTOR_DIR2, LOW); analogWrite(MOTOR_PWM, 200); bluetoothChat.send("Motor running forward"); } else if (cmd == "REVERSE") { digitalWrite(MOTOR_DIR1, LOW); digitalWrite(MOTOR_DIR2, HIGH); analogWrite(MOTOR_PWM, 200); bluetoothChat.send("Motor running reverse"); } else if (cmd == "STOP") { analogWrite(MOTOR_PWM, 0); bluetoothChat.send("Motor stopped"); } else if (cmd.startsWith("SPEED ")) { int speed = cmd.substring(6).toInt(); speed = constrain(speed, 0, 255); analogWrite(MOTOR_PWM, speed); bluetoothChat.send("Motor speed: " + String(speed)); } }); }

BLE vs Bluetooth Clássico - Qual Escolher?

RecursoBLE (Esp32BLE_Chat)Bluetooth Clássico (Esp32Bluetooth_Chat)
Suporte ao iOS? Sim? Não
Suporte ao Android? Sim? Sim
Consumo de EnergiaBaixoMaior
Alcance~30-100m~10-100m
Taxa de DadosMenorMaior
Pareamento NecessárioNão (conexão automática)Sim (pareamento manual)
Melhor ParaDispositivos a bateria, multiplataformaAlta taxa de transferência, somente Android

Tutorial em Vídeo

O vídeo de demonstração abaixo usa o código abaixo:

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-diyables-bluetooth-app-chat */ /* * 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 Configuration const 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 instances DIYables_Esp32BLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Chat app instance DIYables_BluetoothChat bluetoothChat; // LED Pin #define LED_PIN 2 // Variables for periodic messages unsigned long lastMessageTime = 0; const unsigned long MESSAGE_INTERVAL = 10000; // Send message every 10 seconds int messageCount = 0; void setup() { Serial.begin(115200); delay(1000); pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); 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) { String cmd = message; cmd.toUpperCase(); cmd.trim(); Serial.print("Received from App: "); Serial.println(cmd); if (cmd == "LED ON") { digitalWrite(LED_PIN, HIGH); bluetoothChat.send("LED is now: ON"); } else if (cmd == "LED OFF") { digitalWrite(LED_PIN, LOW); bluetoothChat.send("LED is now: OFF"); } else if (cmd == "STATUS") { int state = digitalRead(LED_PIN); String statusMsg = "--- ESP32 STATUS ---\n"; statusMsg += "LED: " + String(state == HIGH ? "ON" : "OFF") + "\n"; statusMsg += "Uptime: " + String(millis() / 1000) + "s\n"; statusMsg += "Chip: ESP32 Dual-Core"; bluetoothChat.send(statusMsg); } else if (cmd == "UPTIME") { bluetoothChat.send("System Uptime: " + String(millis() / 1000) + " seconds"); } else if (cmd == "BLINK") { bluetoothChat.send("Blinking LED..."); for(int i=0; i<3; i++) { digitalWrite(LED_PIN, HIGH); delay(200); digitalWrite(LED_PIN, LOW); delay(200); } bluetoothChat.send("Blink Done!"); } else if (cmd == "HELP") { String help = "--- COMMAND LIST ---\n" "- LED ON / OFF\n" "- STATUS\n" "- UPTIME\n" "- BLINK\n"; bluetoothChat.send(help); } else { bluetoothChat.send("Unknown command. Type 'HELP'."); } }); // 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 (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); }

Solução de Problemas

Problemas Comuns

1. Não consigo encontrar o dispositivo no app

  • Certifique-se de que o ESP32 está ligado e que o sketch foi carregado
  • Para o BLE: Garanta que o Bluetooth e a Localização do seu celular estão ativados
  • Para o Bluetooth Clássico: Pareie o dispositivo primeiro nas configurações de Bluetooth do celular
  • Verifique se o esquema de partição correto está selecionado (Huge APP)

2. As mensagens não aparecem no app

  • Verifique o status da conexão Bluetooth no app
  • Verifique a conexão no Serial Monitor
  • Garanta que as mensagens estão sendo enviadas com bluetoothChat.send()
  • Tente desconectar e reconectar

3. As mensagens de eco não funcionam

  • Verifique se o callback onChatMessage() está configurado corretamente
  • Verifique as mensagens recebidas no Serial Monitor
  • Garanta que a tela do app de chat está selecionada no app para celular

4. A conexão cai com frequência

  • Aproxime-se do ESP32 (reduza a distância)
  • Para o BLE: Verifique se há interferência de outros dispositivos BLE
  • Para o Bluetooth Clássico: Garanta uma alimentação estável para o ESP32
  • Verifique no Serial Monitor se há mensagens de desconexão/reconexão

5. A ponte Serial-Bluetooth não funciona

  • Garanta que o baud rate do Serial Monitor é 115200
  • Defina o fim de linha como "Newline" no Serial Monitor
  • Verifique se bluetooth.isConnected() retorna true
  • Verifique se o código com Serial.available() está no loop()

6. Sketch grande demais / espaço insuficiente

  • No Arduino IDE, vá em Tools > Partition Scheme e selecione "Huge APP (3MB No OTA/1MB SPIFFS)" ou "No OTA (Large APP)"
  • O esquema de partição padrão oferece apenas ~1,2MB para o código do app, o que não é suficiente para as bibliotecas de Bluetooth
  • Esta configuração oferece ~3MB ao sacrificar a partição de OTA (atualização pelo ar)

Dicas de Depuração

Adicione uma depuração completa:

void debugChatMessage(const String& message) { Serial.println("=== Chat Debug ==="); Serial.println("Message: " + message); Serial.println("Length: " + String(message.length())); Serial.println("Free Heap: " + String(ESP.getFreeHeap())); Serial.println("=================="); }

Ideias de Projetos

Projetos de Controle Remoto

  • Controle de robôs por texto, no estilo de comandos de voz
  • Central de comandos de automação residencial
  • Controle de relé sem fio com retorno em texto
  • Posicionamento remoto de servo pelo chat

Projetos de Monitoramento

  • Consulta remota de dados de sensores
  • Verificação da integridade do sistema por comandos no chat
  • Registro de dados com retorno por Bluetooth
  • Depuração e diagnóstico remotos

Projetos Interativos

  • Jogo de quiz ou perguntas e respostas por chat Bluetooth
  • Tutoriais interativos com instruções passo a passo
  • Chatbot com informações do projeto ESP32
  • Ferramenta de configuração remota

Projetos Educacionais

  • Aprender os fundamentos da comunicação Bluetooth
  • Praticar a análise de strings e o tratamento de comandos
  • Entender os padrões de mensagens cliente-servidor
  • Criar protocolos de comunicação personalizados

Integração com Outros Apps Bluetooth

Combine com o Bluetooth Monitor

Use o Chat para comandos e o Monitor para a saída contínua:

bluetoothChat.onChatMessage([](const String& message) { if (message.equalsIgnoreCase("start")) { monitoring = true; bluetoothChat.send("Monitoring started"); } else if (message.equalsIgnoreCase("stop")) { monitoring = false; bluetoothChat.send("Monitoring stopped"); } }); // In loop: send data to monitor when active if (monitoring) { bluetoothMonitor.send("Sensor: " + String(analogRead(34))); }

Combine com o Bluetooth Slider

Use o Chat para definir predefinições de slider e o Slider para o controle fino:

bluetoothChat.onChatMessage([](const String& message) { if (message.equalsIgnoreCase("preset1")) { currentSlider1 = 25; currentSlider2 = 75; bluetoothSlider.send(currentSlider1, currentSlider2); bluetoothChat.send("Applied Preset 1: 25%, 75%"); } else if (message.equalsIgnoreCase("preset2")) { currentSlider1 = 50; currentSlider2 = 50; bluetoothSlider.send(currentSlider1, currentSlider2); bluetoothChat.send("Applied Preset 2: 50%, 50%"); } });

Próximos Passos

Depois de dominar o exemplo Bluetooth Chat, experimente:

  1. Bluetooth Monitor - Para o envio de dados em uma só direção ao app
  2. Bluetooth Slider - Para o controle de valores semelhante ao analógico
  3. Bluetooth Digital Pins - Para o controle discreto de ligar/desligar
  4. Multiple Bluetooth Apps - Combinando o chat com outros controles

Suporte

Para obter ajuda adicional:

  • Consulte a documentação de referência da API
  • Fóruns da comunidade Arduino

※ NOSSAS MENSAGENS

  • 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!