Exemplo de Table Bluetooth com ESP32 - Tutorial de Interface de Exibição de Dados Estruturados

Visão Geral

O exemplo Bluetooth Table oferece uma exibição estruturada de dados chave-valor, acessível pelo app DIYables Bluetooth STEM. Projetado para placas ESP32, com suporte a conexões BLE (Bluetooth Low Energy) e Bluetooth Clássico. Defina linhas nomeadas e atualize seus valores em tempo real — perfeito para painéis, painéis de status de sensores, monitores de sistema e qualquer aplicação que precise de uma apresentação organizada dos dados.

Este exemplo oferece suporte a dois modos de Bluetooth:

  • ESP32 BLE (Bluetooth Low Energy): Funciona no Android e no iOS
  • ESP32 Bluetooth Clássico: Funciona somente no Android. O iOS não oferece suporte ao Bluetooth Clássico. Use o BLE se precisar de suporte ao iOS.
Exemplo de Table Bluetooth com ESP32 - Tutorial de Interface de Exibição de Dados Estruturados

Recursos

  • Linhas Estruturadas: Até 20 linhas de atributos nomeados
  • Atualizações em Tempo Real: Atualize o valor de cada linha individualmente, sem recarregar a tabela inteira
  • Atributos Nomeados: Cada linha tem um rótulo descritivo (por exemplo, "Temperature", "Status")
  • Valores Dinâmicos: Envie qualquer valor de texto para cada linha
  • Sincronização da Estrutura da Tabela: O app solicita a configuração da tabela ao conectar
  • 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 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 o 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 e a porta COM apropriadas.
  • Acesse 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
  • Será solicitado que você instale outras dependências da biblioteca
  • Clique no botão Install All para instalar todas as dependências da biblioteca.
Dependência da biblioteca DIYables Bluetooth para ESP32

Escolha um dos dois modos de Bluetooth abaixo, de acordo com a sua necessidade:

Código ESP32 Bluetooth Clássico (funciona com o app somente no Android)

Observação: O Bluetooth Clássico NÃO é compatível com o iOS. Se você precisa de suporte ao iOS, use o código BLE abaixo.

  • No Arduino IDE, vá em File Examples DIYables Bluetooth Esp32Bluetooth_Table, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - ESP32 Classic Bluetooth Table 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 Table feature: * - Display structured data in a two-column table * - Real-time value updates for each row * - Perfect for sensor dashboards and status displays * * 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 * 3. Use DIYables Bluetooth App to connect and view the table * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothTable.h> #include <platforms/DIYables_Esp32Bluetooth.h> // Create Bluetooth instances DIYables_Esp32Bluetooth bluetooth("ESP32_Table"); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Table app instance DIYables_BluetoothTable bluetoothTable; // Variables for demo data unsigned long lastUpdate = 0; const unsigned long UPDATE_INTERVAL = 1000; // Update every second int counter = 0; void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 Table Example"); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add table app to server bluetoothServer.addApp(&bluetoothTable); // Define table structure (add rows with attribute names) bluetoothTable.addRow("Temperature"); bluetoothTable.addRow("Humidity"); bluetoothTable.addRow("Pressure"); bluetoothTable.addRow("Counter"); bluetoothTable.addRow("Uptime"); bluetoothTable.addRow("Free Heap"); bluetoothTable.addRow("CPU Freq"); bluetoothTable.addRow("Status"); Serial.print("Table rows defined: "); Serial.println(bluetoothTable.getRowCount()); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); // Send table structure bluetoothTable.sendTableStructure(); // Send initial values updateTableValues(); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Optional: Handle requests for table data bluetoothTable.onDataRequest([]() { Serial.println("App requested table data"); bluetoothTable.sendTableStructure(); updateTableValues(); }); Serial.println("Waiting for Bluetooth connection..."); } void updateTableValues() { // TODO: Replace with actual sensor readings // Simulated temperature (20-30°C) float temperature = 20.0 + random(0, 100) / 10.0; bluetoothTable.sendValueUpdate("Temperature", String(temperature, 1) + " °C"); // Simulated humidity (40-60%) int humidity = 40 + random(0, 21); bluetoothTable.sendValueUpdate("Humidity", String(humidity) + " %"); // Simulated pressure (1000-1020 hPa) int pressure = 1000 + random(0, 21); bluetoothTable.sendValueUpdate("Pressure", String(pressure) + " hPa"); // Counter value bluetoothTable.sendValueUpdate("Counter", String(counter)); counter++; // Uptime (in seconds) unsigned long uptime = millis() / 1000; String uptimeStr = String(uptime / 3600) + "h " + String((uptime % 3600) / 60) + "m " + String(uptime % 60) + "s"; bluetoothTable.sendValueUpdate("Uptime", uptimeStr); // ESP32-specific: Free heap memory bluetoothTable.sendValueUpdate("Free Heap", String(ESP.getFreeHeap()) + " bytes"); // ESP32-specific: CPU frequency bluetoothTable.sendValueUpdate("CPU Freq", String(ESP.getCpuFreqMHz()) + " MHz"); // Status bluetoothTable.sendValueUpdate("Status", counter % 2 == 0 ? "Running" : "Active"); Serial.println("Table values updated"); } void loop() { // Handle Bluetooth server communications bluetoothServer.loop(); // Update table values periodically (only when connected) if (bluetooth.isConnected() && millis() - lastUpdate >= UPDATE_INTERVAL) { lastUpdate = millis(); updateTableValues(); } delay(10); }
  • Clique no botão Upload do Arduino IDE para carregar o código no ESP32
  • Abra o Serial Monitor
  • Confira o resultado no Serial Monitor. Ele deve ficar como 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 Table Example Waiting for Bluetooth connection...
Ln 11, Col 1
ESP32 Dev Module on COM15
2

Código ESP32 BLE (funciona com o app no Android e no iOS)

  • No Arduino IDE, vá em File Examples DIYables Bluetooth Esp32BLE_Table, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - ESP32 BLE Table Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Table feature: * - Display structured data in a two-column table * - Real-time value updates for each row * - Perfect for sensor dashboards and status displays * * 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 * 3. Use DIYables Bluetooth App to connect and view the table * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothTable.h> #include <platforms/DIYables_Esp32BLE.h> // BLE Configuration const char* DEVICE_NAME = "ESP32BLE_Table"; 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 Table app instance DIYables_BluetoothTable bluetoothTable; // Variables for demo data unsigned long lastUpdate = 0; const unsigned long UPDATE_INTERVAL = 1000; int counter = 0; void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 BLE Table Example"); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add table app to server bluetoothServer.addApp(&bluetoothTable); // Define table structure bluetoothTable.addRow("Temperature"); bluetoothTable.addRow("Humidity"); bluetoothTable.addRow("Pressure"); bluetoothTable.addRow("Counter"); bluetoothTable.addRow("Uptime"); bluetoothTable.addRow("Free Heap"); bluetoothTable.addRow("Status"); Serial.print("Table rows defined: "); Serial.println(bluetoothTable.getRowCount()); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); bluetoothTable.sendTableStructure(); updateTableValues(); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); bluetoothTable.onDataRequest([]() { Serial.println("App requested table data"); bluetoothTable.sendTableStructure(); updateTableValues(); }); Serial.println("Waiting for Bluetooth connection..."); } void updateTableValues() { float temperature = 20.0 + random(0, 100) / 10.0; bluetoothTable.sendValueUpdate("Temperature", String(temperature, 1) + " °C"); int humidity = 40 + random(0, 21); bluetoothTable.sendValueUpdate("Humidity", String(humidity) + " %"); int pressure = 1000 + random(0, 21); bluetoothTable.sendValueUpdate("Pressure", String(pressure) + " hPa"); bluetoothTable.sendValueUpdate("Counter", String(counter)); counter++; unsigned long uptime = millis() / 1000; String uptimeStr = String(uptime / 3600) + "h " + String((uptime % 3600) / 60) + "m " + String(uptime % 60) + "s"; bluetoothTable.sendValueUpdate("Uptime", uptimeStr); bluetoothTable.sendValueUpdate("Free Heap", String(ESP.getFreeHeap()) + " bytes"); bluetoothTable.sendValueUpdate("Status", counter % 2 == 0 ? "Running" : "Active"); Serial.println("Table values updated"); } void loop() { bluetoothServer.loop(); if (bluetooth.isConnected() && millis() - lastUpdate >= UPDATE_INTERVAL) { lastUpdate = millis(); updateTableValues(); } delay(10); }
  • Clique no botão Upload do Arduino IDE para carregar o código no ESP32
  • Abra o Serial Monitor
  • Confira o resultado no Serial Monitor. Ele deve ficar como 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 Table Example Waiting for Bluetooth connection...
Ln 11, Col 1
ESP32 Dev Module on COM15
2

App para Celular

  • Instale o app DIYables Bluetooth no seu smartphone: Android | iOS
  • Se você estiver usando o código ESP32 Bluetooth Clássico, é preciso parear o ESP32 com o seu celular Android antes de abrir o app:
    • Vá em Configurações > Bluetooth do seu celular
    • Verifique se o Bluetooth está ligado
    • Seu celular vai procurar os dispositivos disponíveis
    • Encontre e toque em "ESP32_Table" 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 ESP32 BLE, não é necessário parear. Basta ir para o próximo passo.
  • Abra o app DIYables Bluetooth
  • 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 procurar e conectar a dispositivos Bluetooth
    • Permissão de Localização (somente Android 11 e anteriores) - exigida por versões mais antigas do Android para procurar dispositivos BLE
  • Verifique se o Bluetooth está ligado no seu celular
  • Na tela inicial, toque no botão Connect. O app vai procurar dispositivos BLE e Bluetooth Clássico.
App DIYables Bluetooth - Tela Inicial com Botão de Busca
  • Encontre e toque no seu dispositivo nos resultados da busca para conectar:
    • Para Bluetooth Clássico: toque em "ESP32_Table"
    • Para BLE: toque em "ESP32BLE_Table"
  • Depois de conectado, o app volta automaticamente para a tela inicial. Selecione o app Table no menu de apps.
App DIYables Bluetooth - Tela Inicial com o App Table

Observação: Você pode tocar no ícone de configurações na tela inicial para ocultar/mostrar apps. Para mais detalhes, consulte o Manual do Usuário do DIYables Bluetooth App.

  • A tabela será preenchida com os nomes dos atributos e seus valores atuais
App DIYables Bluetooth - Tela da Table

Agora olhe de volta para o 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! App requested table data Sent table structure Temperature: 25.3 Humidity: 62% Pressure: 1013 hPa Counter: 1 Uptime: 0h 0m 5s Free Heap: 245780 Status: Running
Ln 11, Col 1
ESP32 Dev Module on COM15
2
  • Veja os valores da tabela sendo atualizados em tempo real no app

Personalização Criativa - Adapte o Código ao Seu Projeto

Defina as Linhas da Tabela

Adicione linhas de atributos à tabela (até 20 linhas no máximo):

// Add rows during setup bluetoothTable.addRow("Temperature"); bluetoothTable.addRow("Humidity"); bluetoothTable.addRow("Pressure"); bluetoothTable.addRow("Status"); bluetoothTable.addRow("Uptime"); // Check row count int rows = bluetoothTable.getRowCount(); Serial.println("Total rows: " + String(rows)); // Get attribute name by index String attr = bluetoothTable.getAttribute(0); // Returns "Temperature"

Atualize os Valores das Linhas

Atualize o valor de cada linha pelo nome do atributo ou pelo índice:

// Update by attribute name bluetoothTable.sendValueUpdate("Temperature", "25.3 °C"); bluetoothTable.sendValueUpdate("Humidity", "62%"); bluetoothTable.sendValueUpdate("Status", "Running"); // Update by row index (0-based) bluetoothTable.sendValueUpdate(0, "25.3 °C"); // First row bluetoothTable.sendValueUpdate(1, "62%"); // Second row

Tratar as Solicitações de Dados do App

Quando o app se conecta ou solicita uma atualização:

bluetoothTable.onDataRequest([]() { Serial.println("App requested table data"); bluetoothTable.sendTableStructure(); // Send row names // Send current values for all rows bluetoothTable.sendValueUpdate("Temperature", String(temperature, 1) + " °C"); bluetoothTable.sendValueUpdate("Humidity", String(humidity) + "%"); bluetoothTable.sendValueUpdate("Status", "Online"); });

Limpar e Reconstruir a Tabela

// Clear all rows bluetoothTable.clearTable(); // Add new rows bluetoothTable.addRow("Sensor A"); bluetoothTable.addRow("Sensor B"); // Send updated structure to app bluetoothTable.sendTableStructure();

Tratar Eventos de Conexão

bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); });

Como Usar a Table

Interface do App

A interface da tabela no app DIYables Bluetooth mostra:

  • Coluna de Atributos: Rótulos das linhas definidos por addRow()
  • Coluna de Valores: Valores atuais atualizados por sendValueUpdate()
  • Atualização Automática: Os valores são atualizados em tempo real à medida que chegam

Limites da Tabela

  • No máximo 20 linhas por tabela (MAX_TABLE_ROWS = 20)
  • Os nomes dos atributos devem ser concisos, mas descritivos
  • Os valores são exibidos como texto

Exemplos de Programação

Painel de Sensores

// Define sensor dashboard rows bluetoothTable.addRow("Temperature"); bluetoothTable.addRow("Humidity"); bluetoothTable.addRow("Pressure"); bluetoothTable.addRow("Light Level"); bluetoothTable.addRow("Air Quality"); void loop() { bluetoothServer.loop(); static unsigned long lastUpdate = 0; if (millis() - lastUpdate >= 2000) { lastUpdate = millis(); float temp = readTemperature(); float hum = readHumidity(); float press = readPressure(); int light = analogRead(34); int airQuality = analogRead(35); bluetoothTable.sendValueUpdate("Temperature", String(temp, 1) + " °C"); bluetoothTable.sendValueUpdate("Humidity", String(hum, 0) + "%"); bluetoothTable.sendValueUpdate("Pressure", String(press, 0) + " hPa"); bluetoothTable.sendValueUpdate("Light Level", String(map(light, 0, 4095, 0, 100)) + "%"); bluetoothTable.sendValueUpdate("Air Quality", airQuality < 1000 ? "Good" : "Poor"); } delay(10); }

Monitor de Status do Sistema

bluetoothTable.addRow("Uptime"); bluetoothTable.addRow("Free Heap"); bluetoothTable.addRow("CPU Temp"); bluetoothTable.addRow("WiFi Signal"); bluetoothTable.addRow("Clients"); bluetoothTable.addRow("Status"); void updateSystemStatus() { unsigned long uptime = millis() / 1000; int hours = uptime / 3600; int minutes = (uptime % 3600) / 60; int seconds = uptime % 60; bluetoothTable.sendValueUpdate("Uptime", String(hours) + "h " + String(minutes) + "m " + String(seconds) + "s"); bluetoothTable.sendValueUpdate("Free Heap", String(ESP.getFreeHeap()) + " bytes"); bluetoothTable.sendValueUpdate("CPU Temp", String(temperatureRead(), 1) + " °C"); bluetoothTable.sendValueUpdate("Status", "Online"); }

Tabela de Status dos Pinos GPIO

const int PINS[] = {2, 4, 5, 12, 13, 14, 15, 16}; const int NUM_PINS = sizeof(PINS) / sizeof(PINS[0]); void setup() { // ... Bluetooth setup ... for (int i = 0; i < NUM_PINS; i++) { pinMode(PINS[i], INPUT); bluetoothTable.addRow("GPIO " + String(PINS[i])); } } void loop() { bluetoothServer.loop(); static unsigned long lastUpdate = 0; if (millis() - lastUpdate >= 1000) { lastUpdate = millis(); for (int i = 0; i < NUM_PINS; i++) { int state = digitalRead(PINS[i]); bluetoothTable.sendValueUpdate("GPIO " + String(PINS[i]), state == HIGH ? "HIGH ?" : "LOW ?"); } } delay(10); }

Matriz de Sensores Analógicos

struct SensorConfig { String name; int pin; String unit; float scale; }; SensorConfig sensors[] = { {"Temperature", 34, "°C", 0.0488}, {"Humidity", 35, "%", 0.0244}, {"Light", 36, "lux", 0.244}, {"Pressure", 39, "hPa", 0.488} }; const int NUM_SENSORS = sizeof(sensors) / sizeof(sensors[0]); void setup() { // ... Bluetooth setup ... for (int i = 0; i < NUM_SENSORS; i++) { bluetoothTable.addRow(sensors[i].name); } } void loop() { bluetoothServer.loop(); static unsigned long lastUpdate = 0; if (millis() - lastUpdate >= 2000) { lastUpdate = millis(); for (int i = 0; i < NUM_SENSORS; i++) { int raw = analogRead(sensors[i].pin); float value = raw * sensors[i].scale; bluetoothTable.sendValueUpdate(sensors[i].name, String(value, 1) + " " + sensors[i].unit); } } delay(10); }

Técnicas Avançadas de Programação

Formatação Condicional com Emojis

void updateTemperatureRow(float temp) { String status; if (temp < 10) { status = "❄️ " + String(temp, 1) + " °C (Cold)"; } else if (temp < 30) { status = "✅ " + String(temp, 1) + " °C (Normal)"; } else { status = "🔥 " + String(temp, 1) + " °C (Hot!)"; } bluetoothTable.sendValueUpdate("Temperature", status); }

Atualizações Orientadas a Eventos

float lastTemp = 0; float threshold = 0.5; // Only update on significant change void loop() { bluetoothServer.loop(); float temp = readTemperature(); if (abs(temp - lastTemp) >= threshold) { lastTemp = temp; bluetoothTable.sendValueUpdate("Temperature", String(temp, 1) + " °C"); bluetoothTable.sendValueUpdate("Last Change", getTimestamp()); } delay(100); }

Ideias de Integração de Hardware

Tabela de Estação Meteorológica com BME280

Conecte um sensor BME280 para exibir temperatura, umidade e pressão na tabela.

Painel com Vários Sensores

Conecte vários sensores (DHT22, BMP280, LDR, MQ-135) e exiba todas as leituras como linhas.

Painel de Informações do Dispositivo

Exiba as informações do sistema do ESP32: modelo do chip, tamanho da flash, heap livre, uptime e endereço MAC.

BLE vs Bluetooth Clássico - Qual Escolher?

RecursoBLE (Esp32BLE_Table)Bluetooth Clássico (Esp32Bluetooth_Table)
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)
Ideal ParaAlimentado por bateria, multiplataformaAlta taxa de transferência, somente Android

Tutorial em Vídeo

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

/* * 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-table */ /* * DIYables Bluetooth Library - ESP32 BLE Table Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Table feature: * - Display structured data in a two-column table * - Real-time value updates for each row * - Perfect for sensor dashboards and status displays * * 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 * 3. Use DIYables Bluetooth App to connect and view the table * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothTable.h> #include <platforms/DIYables_Esp32BLE.h> #include <DHT.h> // BLE Configuration const char* DEVICE_NAME = "ESP32BLE_Table"; 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 Table app instance DIYables_BluetoothTable bluetoothTable; #define LED_BUILTIN 22 #define DHTPIN 23 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); // Variables for demo data unsigned long lastUpdate = 0; const unsigned long UPDATE_INTERVAL = 1000; bool ledState = false; int counter = 0; void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 BLE Table Example"); // Initialize built-in LED pinMode(LED_BUILTIN, OUTPUT); dht.begin(); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add table app to server bluetoothServer.addApp(&bluetoothTable); // Define table structure bluetoothTable.addRow("Temperature"); bluetoothTable.addRow("Humidity"); bluetoothTable.addRow("LED Status"); bluetoothTable.addRow("Pressure"); bluetoothTable.addRow("Counter"); bluetoothTable.addRow("Uptime"); bluetoothTable.addRow("Free Heap"); bluetoothTable.addRow("Status"); Serial.print("Table rows defined: "); Serial.println(bluetoothTable.getRowCount()); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); bluetoothTable.sendTableStructure(); updateTableValues(); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); bluetoothTable.onDataRequest([]() { Serial.println("App requested table data"); bluetoothTable.sendTableStructure(); updateTableValues(); }); Serial.println("Waiting for Bluetooth connection..."); } void updateTableValues() { //float temperature = 20.0 + random(0, 100) / 10.0; float temperature = dht.readTemperature(); bluetoothTable.sendValueUpdate("Temperature", String(temperature, 1) + " °C"); //int humidity = 40 + random(0, 21); int humidity = dht.readHumidity(); bluetoothTable.sendValueUpdate("Humidity", String(humidity) + " %"); // Check if any reads failed and exit early (to try again). if (isnan(humidity) || isnan(temperature)) { Serial.println(F("Failed to read from DHT sensor!")); return; } int pressure = 1000 + random(0, 21); bluetoothTable.sendValueUpdate("Pressure", String(pressure) + " hPa"); bluetoothTable.sendValueUpdate("Counter", String(counter)); counter++; unsigned long uptime = millis() / 1000; String uptimeStr = String(uptime / 3600) + "h " + String((uptime % 3600) / 60) + "m " + String(uptime % 60) + "s"; bluetoothTable.sendValueUpdate("Uptime", uptimeStr); bluetoothTable.sendValueUpdate("Free Heap", String(ESP.getFreeHeap()) + " bytes"); bluetoothTable.sendValueUpdate("Status", counter % 2 == 0 ? "Running" : "Active"); Serial.println("Table values updated"); } void loop() { bluetoothServer.loop(); if (bluetooth.isConnected() && millis() - lastUpdate >= UPDATE_INTERVAL) { lastUpdate = millis(); updateTableValues(); } // Toggle LED every 3 seconds static unsigned long lastLedToggle = 0; if (millis() - lastLedToggle > 3000) { ledState = !ledState; digitalWrite(LED_BUILTIN, ledState); // Send LED status update to web interface bluetoothTable.sendValueUpdate("LED Status", ledState ? "ON" : "OFF"); lastLedToggle = millis(); } delay(10); }

Solução de Problemas

Problemas Comuns

1. Não consigo encontrar o dispositivo no app

  • Verifique se o ESP32 está ligado e se o sketch foi carregado
  • Para BLE: verifique se o Bluetooth e a Localização do seu celular estão ativados
  • Para 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. A tabela não mostra dados

  • Garanta que sendTableStructure() seja chamado no callback onDataRequest
  • Confirme que as linhas foram adicionadas com addRow() antes de enviar atualizações
  • Verifique no Serial Monitor a mensagem "App requested table data"

3. Os valores não estão atualizando

  • Confirme que o nome do atributo em sendValueUpdate() corresponde exatamente ao que foi adicionado com addRow()
  • Verifique se o timer do seu intervalo de atualização está funcionando
  • Garanta que o Bluetooth ainda esteja conectado

4. Faltam linhas na tabela

  • No máximo 20 linhas são suportadas
  • Use getRowCount() para confirmar que todas as linhas foram adicionadas
  • As linhas devem ser adicionadas antes de enviar a estrutura da tabela

5. A conexão cai com frequência

  • Chegue mais perto do ESP32 (reduza a distância)
  • Para BLE: verifique se há interferência de outros dispositivos BLE
  • Para Bluetooth Clássico: garanta uma fonte de alimentação estável para o ESP32

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
  • Essa configuração oferece ~3MB ao sacrificar a partição de OTA (atualização over-the-air)

Dicas de Depuração

Adicione uma depuração completa:

void debugTable() { Serial.println("=== Table Debug ==="); Serial.println("Row Count: " + String(bluetoothTable.getRowCount())); for (int i = 0; i < bluetoothTable.getRowCount(); i++) { Serial.println("Row " + String(i) + ": " + bluetoothTable.getAttribute(i)); } Serial.println("==================="); }

Ideias de Projetos

Painéis de Monitoramento

  • Exibição de estação meteorológica (temperatura, umidade, pressão, vento)
  • Monitor de status de servidor/rede
  • Painel de cuidados com plantas (umidade do solo, luz, temperatura)
  • Monitor de aquário (temperatura, pH, TDS)

Informações do Sistema

  • Tabela de diagnósticos do sistema ESP32
  • Detalhes da conexão WiFi
  • Acompanhamento do uso de memória
  • Exibição do status da bateria

Registro de Dados

  • Acompanhamento de mín/máx/média dos sensores
  • Exibição de contador de eventos
  • Estatísticas de tempo (tempo de resposta, uptime)
  • Resumo do estado dos pinos de E/S

Automação Residencial

  • Exibição de temperatura cômodo por cômodo
  • Visão geral do status dos dispositivos
  • Resumo do consumo de energia
  • Status dos sensores de segurança

Integração com Outros Apps Bluetooth

Combine com o Bluetooth Plotter

Exiba os valores na tabela e visualize as tendências no plotter:

float temperature = 0; void loop() { bluetoothServer.loop(); static unsigned long lastUpdate = 0; if (millis() - lastUpdate >= 2000) { lastUpdate = millis(); temperature = readTemperature(); // Update table bluetoothTable.sendValueUpdate("Temperature", String(temperature, 1) + " °C"); bluetoothTable.sendValueUpdate("Status", temperature > 30 ? "Warning" : "Normal"); // Plot trend bluetoothPlotter.send(temperature); } delay(10); }

Combine com o Bluetooth Monitor

Use a tabela para dados estruturados e o monitor para mensagens de log:

bluetoothTable.sendValueUpdate("Temperature", String(temp, 1) + " °C"); bluetoothMonitor.send("[INFO] Temperature: " + String(temp, 1) + " °C"); if (temp > 40) { bluetoothTable.sendValueUpdate("Status", "? ALERT"); bluetoothMonitor.send("[ALERT] High temperature detected!"); }

Próximos Passos

Depois de dominar o exemplo Bluetooth Table, experimente:

  1. Bluetooth Monitor - Para registro de texto livre
  2. Bluetooth Plotter - Para visualizar tendências de dados
  3. Bluetooth Temperature - Para exibição dedicada de temperatura
  4. Multiple Bluetooth Apps - Combinando a tabela com outros displays

Suporte

Para obter mais ajuda:

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