Exemplo de Vários Aplicativos Bluetooth para Arduino Nano ESP32 - Tutorial BLE Tudo-em-Um

Visão Geral

Este exemplo demonstra como executar 9 widgets de aplicativos Bluetooth ao mesmo tempo em um único Arduino Nano ESP32 usando BLE. Com BLE (Bluetooth Low Energy), o sketch combina Monitor, Chat, Slider, Joystick, Temperature, Plotter, Table, Analog Gauge e Rotator em um único sketch. Todos os widgets compartilham uma única conexão BLE e podem interagir entre si. Adequado para painéis completos, projetos IoT complexos e para aprender vários tipos de widgets de uma só vez.

Observação: O Arduino Nano ESP32 suporta apenas BLE — o Bluetooth Clássico não é suportado. O DIYables Bluetooth App funciona em Android e iOS com BLE.

Exemplo de Vários Aplicativos Bluetooth para Arduino Nano ESP32 - Tutorial BLE Tudo-em-Um

Recursos

  • 9 Widgets em Um: Monitor, Chat, Slider, Joystick, Temperature, Plotter, Table, Analog Gauge, Rotator
  • Interação entre Widgets: O slider atualiza o medidor e a tabela; o joystick atualiza a tabela, etc.
  • Conexão BLE Única: Todos os widgets compartilham uma conexão de forma eficiente
  • Atualizações em Tempo Real: Cada widget é atualizado no seu próprio intervalo configurado
  • Painel Completo: Veja todos os dados de um único dispositivo
  • Suporte a Android e iOS: O BLE é compatível com as duas plataformas
  • Sem Necessidade de Pareamento: O BLE conecta sem pareamento manual

Aplicativos Incluídos

AppDescriçãoIntervalo de Atualização
MonitorExibição de status em texto5 segundos
ChatMensagens de texto bidirecionaisSob demanda
SliderControle de valores (0-255)Ao mudar
JoystickControle de posição 2DAo mudar
TemperatureMedidor de temperatura (-10 a 50°C)2 segundos
PlotterGráfico de dados em tempo real100ms
TableDados estruturados (10 linhas)5 segundos
Analog GaugeMedidor estilo mostrador (0-100%)3 segundos
RotatorControle de ângulo (contínuo)Ao mudar

Hardware Necessário

1×Arduino Nano ESP32
1×Cabo USB Tipo-A para Tipo-C (para PC com USB-A)
1×Cabo USB Tipo-C para Tipo-C (para PC com USB-C)
1×(Recomendado) Placa de Expansão com Bornes de Parafuso para Arduino Nano
1×(Recomendado) Placa de Expansão Breakout para Arduino Nano
1×(Recomendado) Divisor de Alimentação para Arduino Nano ESP32

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
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.

Código Arduino Nano ESP32

Passos Rápidos

  • Novo no Arduino Nano ESP32? Comece pelo guia de primeiros passos do Arduino Nano ESP32.
  • Conecte o Arduino Nano ESP32 ao seu computador via USB.
  • Abra a Arduino IDE.
  • Selecione a placa Arduino Nano ESP32 e a porta COM correta.
  • Clique no ícone Libraries na barra lateral esquerda.
  • Pesquise por "DIYables Bluetooth" e selecione a biblioteca DIYables Bluetooth da DIYables.
  • Clique em Install.
Biblioteca DIYables Bluetooth para Arduino Nano ESP32
  • Quando for solicitado a instalar as dependências, clique em Install All.
Dependência do DIYables Bluetooth para Arduino Nano ESP32

Código BLE

  • Na Arduino IDE, abra File Examples DIYables Bluetooth ArduinoBLE_MultipleApps, ou cole o código no editor.
/* * DIYables Bluetooth Library - ESP32 BLE Multiple Apps Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates how to use multiple Bluetooth apps simultaneously: * - Monitor, Chat, Slider, Joystick, Temperature, Plotter, * Table, Analog Gauge, Rotator * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothMonitor.h> #include <DIYables_BluetoothChat.h> #include <DIYables_BluetoothSlider.h> #include <DIYables_BluetoothJoystick.h> #include <DIYables_BluetoothTemperature.h> #include <DIYables_BluetoothPlotter.h> #include <DIYables_BluetoothTable.h> #include <DIYables_BluetoothAnalogGauge.h> #include <DIYables_BluetoothRotator.h> #include <platforms/DIYables_Esp32BLE.h> // BLE Configuration const char* DEVICE_NAME = "ESP32BLE Multi-App"; 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 app instances DIYables_BluetoothMonitor bluetoothMonitor; DIYables_BluetoothChat bluetoothChat; DIYables_BluetoothSlider bluetoothSlider(0, 255, 1); DIYables_BluetoothJoystick bluetoothJoystick(false, 5); DIYables_BluetoothTemperature bluetoothTemperature(-10.0, 50.0, "°C"); DIYables_BluetoothPlotter bluetoothPlotter; DIYables_BluetoothTable bluetoothTable; DIYables_BluetoothAnalogGauge bluetoothGauge(0.0, 100.0, "%"); DIYables_BluetoothRotator bluetoothRotator(ROTATOR_MODE_CONTINUOUS); // State variables int currentSlider1 = 128; int currentSlider2 = 64; int currentJoystickX = 0; int currentJoystickY = 0; float currentTemperature = 25.0; float currentGaugeValue = 50.0; float currentRotatorAngle = 0.0; int messageCount = 0; // Timing variables unsigned long lastMonitorUpdate = 0; unsigned long lastTempUpdate = 0; unsigned long lastPlotUpdate = 0; unsigned long lastTableUpdate = 0; unsigned long lastGaugeUpdate = 0; float plotPhase = 0; void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 BLE Multiple Apps Example"); pinMode(2, OUTPUT); digitalWrite(2, LOW); bluetoothServer.begin(); bluetoothServer.addApp(&bluetoothMonitor); bluetoothServer.addApp(&bluetoothChat); bluetoothServer.addApp(&bluetoothSlider); bluetoothServer.addApp(&bluetoothJoystick); bluetoothServer.addApp(&bluetoothTemperature); bluetoothServer.addApp(&bluetoothPlotter); bluetoothServer.addApp(&bluetoothTable); bluetoothServer.addApp(&bluetoothGauge); bluetoothServer.addApp(&bluetoothRotator); Serial.print("Registered apps: "); Serial.println(bluetoothServer.getAppCount()); bluetoothPlotter.setPlotTitle("Sensor Data"); bluetoothPlotter.setAxisLabels("Time", "Value"); bluetoothPlotter.setYAxisRange(-1.5, 1.5); bluetoothPlotter.setMaxSamples(100); bluetoothPlotter.setLegendLabels("Sine", "Cosine", "Random"); bluetoothTable.addRow("Status"); bluetoothTable.addRow("Uptime"); bluetoothTable.addRow("Slider 1"); bluetoothTable.addRow("Slider 2"); bluetoothTable.addRow("Joystick X"); bluetoothTable.addRow("Joystick Y"); bluetoothTable.addRow("Temperature"); bluetoothTable.addRow("Gauge Value"); bluetoothTable.addRow("Rotator Angle"); bluetoothTable.addRow("Messages"); setupCallbacks(); Serial.println("Waiting for Bluetooth connection..."); } void setupCallbacks() { bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); digitalWrite(2, HIGH); bluetoothMonitor.send("=== ESP32 BLE Multi-App Connected ==="); bluetoothMonitor.send("All apps are ready!"); bluetoothChat.send("Hello! ESP32 BLE Multi-App is connected."); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); digitalWrite(2, LOW); }); bluetoothMonitor.onMonitorMessage([](const String& message) { Serial.println("Monitor cmd: " + message); if (message == "HELP") { bluetoothMonitor.send("Commands: STATUS, HELP, LED_ON, LED_OFF, HEAP"); } else if (message == "STATUS") { bluetoothMonitor.send("Slider1=" + String(currentSlider1) + " Slider2=" + String(currentSlider2)); bluetoothMonitor.send("Joystick X=" + String(currentJoystickX) + " Y=" + String(currentJoystickY)); bluetoothMonitor.send("Temp=" + String(currentTemperature, 1) + "°C"); bluetoothMonitor.send("Gauge=" + String(currentGaugeValue, 1) + "%"); bluetoothMonitor.send("Rotator=" + String(currentRotatorAngle, 0) + "°"); } else if (message == "LED_ON") { digitalWrite(2, HIGH); bluetoothMonitor.send("LED turned ON"); } else if (message == "LED_OFF") { digitalWrite(2, LOW); bluetoothMonitor.send("LED turned OFF"); } else if (message == "HEAP") { bluetoothMonitor.send("Free heap: " + String(ESP.getFreeHeap()) + " bytes"); } else { bluetoothMonitor.send("Unknown: " + message + " (type HELP)"); } }); bluetoothChat.onChatMessage([](const String& message) { Serial.println("Chat: " + message); bluetoothChat.send("Echo: " + message); if (message.equalsIgnoreCase("ping")) { bluetoothChat.send("pong!"); } else if (message.equalsIgnoreCase("status")) { bluetoothChat.send("Uptime: " + String(millis() / 1000) + "s, Apps: " + String(bluetoothServer.getAppCount())); } }); bluetoothSlider.onSliderValue([](int slider1, int slider2) { currentSlider1 = slider1; currentSlider2 = slider2; Serial.print("Slider 1: "); Serial.print(slider1); Serial.print(", Slider 2: "); Serial.println(slider2); currentGaugeValue = map(slider1, 0, 255, 0, 100); bluetoothGauge.send(currentGaugeValue); bluetoothTable.sendValueUpdate("Slider 1", String(slider1)); bluetoothTable.sendValueUpdate("Slider 2", String(slider2)); bluetoothTable.sendValueUpdate("Gauge Value", String(currentGaugeValue, 1) + "%"); }); bluetoothSlider.onGetConfig([]() { bluetoothSlider.send(currentSlider1, currentSlider2); }); bluetoothJoystick.onJoystickValue([](int x, int y) { currentJoystickX = x; currentJoystickY = y; Serial.print("Joystick X: "); Serial.print(x); Serial.print(", Y: "); Serial.println(y); bluetoothTable.sendValueUpdate("Joystick X", String(x)); bluetoothTable.sendValueUpdate("Joystick Y", String(y)); }); bluetoothJoystick.onGetConfig([]() { bluetoothJoystick.send(currentJoystickX, currentJoystickY); }); bluetoothTemperature.onTemperatureRequest([]() { bluetoothTemperature.send(currentTemperature); }); bluetoothPlotter.onDataRequest([]() { Serial.println("Plotter data requested"); }); bluetoothTable.onDataRequest([]() { Serial.println("Table data requested"); bluetoothTable.sendTableStructure(); updateAllTableValues(); }); bluetoothGauge.onValueRequest([]() { bluetoothGauge.send(currentGaugeValue); }); bluetoothRotator.onRotatorAngle([](float angle) { currentRotatorAngle = angle; Serial.print("Rotator: "); Serial.print(angle); Serial.println("°"); bluetoothTable.sendValueUpdate("Rotator Angle", String(angle, 0) + "°"); }); } void updateAllTableValues() { bluetoothTable.sendValueUpdate("Status", "Running"); unsigned long uptime = millis() / 1000; String uptimeStr; if (uptime >= 60) { uptimeStr = String(uptime / 60) + "m " + String(uptime % 60) + "s"; } else { uptimeStr = String(uptime) + "s"; } bluetoothTable.sendValueUpdate("Uptime", uptimeStr); bluetoothTable.sendValueUpdate("Slider 1", String(currentSlider1)); bluetoothTable.sendValueUpdate("Slider 2", String(currentSlider2)); bluetoothTable.sendValueUpdate("Joystick X", String(currentJoystickX)); bluetoothTable.sendValueUpdate("Joystick Y", String(currentJoystickY)); bluetoothTable.sendValueUpdate("Temperature", String(currentTemperature, 1) + " °C"); bluetoothTable.sendValueUpdate("Gauge Value", String(currentGaugeValue, 1) + "%"); bluetoothTable.sendValueUpdate("Rotator Angle", String(currentRotatorAngle, 0) + "°"); bluetoothTable.sendValueUpdate("Messages", String(messageCount)); } void loop() { bluetoothServer.loop(); if (!bluetooth.isConnected()) { delay(10); return; } if (millis() - lastMonitorUpdate >= 5000) { lastMonitorUpdate = millis(); messageCount++; bluetoothMonitor.send("[INFO] Heartbeat #" + String(messageCount) + " - Uptime: " + String(millis() / 1000) + "s"); } if (millis() - lastTempUpdate >= 2000) { lastTempUpdate = millis(); static float tempOffset = 0; tempOffset += random(-10, 11) / 10.0; if (tempOffset > 5.0) tempOffset = 5.0; if (tempOffset < -5.0) tempOffset = -5.0; currentTemperature = 25.0 + tempOffset; bluetoothTemperature.send(currentTemperature); bluetoothTable.sendValueUpdate("Temperature", String(currentTemperature, 1) + " °C"); } if (millis() - lastPlotUpdate >= 100) { lastPlotUpdate = millis(); float sine = sin(plotPhase); float cosine = cos(plotPhase); float noise = random(-50, 51) / 100.0; bluetoothPlotter.send(sine, cosine, noise); plotPhase += 0.1; if (plotPhase > 2 * PI) plotPhase = 0; } if (millis() - lastTableUpdate >= 5000) { lastTableUpdate = millis(); unsigned long uptime = millis() / 1000; String uptimeStr; if (uptime >= 60) { uptimeStr = String(uptime / 60) + "m " + String(uptime % 60) + "s"; } else { uptimeStr = String(uptime) + "s"; } bluetoothTable.sendValueUpdate("Uptime", uptimeStr); bluetoothTable.sendValueUpdate("Messages", String(messageCount)); } if (millis() - lastGaugeUpdate >= 3000) { lastGaugeUpdate = millis(); float sensorValue = 50.0 + 30.0 * sin(millis() / 10000.0); currentGaugeValue = sensorValue; bluetoothGauge.send(currentGaugeValue); bluetoothTable.sendValueUpdate("Gauge Value", String(currentGaugeValue, 1) + "%"); } delay(10); }
  • Clique em Upload para gravar o sketch na placa.
  • Abra o Serial Monitor.
  • A saída do Serial Monitor deve ficar assim:
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Nano ESP32
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Nano ESP32' on 'COM15')
New Line
9600 baud
DIYables Bluetooth - Multiple Apps Example Waiting for Bluetooth connection...
Ln 11, Col 1
Arduino Nano ESP32 on COM15
2

Aplicativo Móvel

  • Instale o DIYables Bluetooth App no seu smartphone: Android | iOS

Observação: O DIYables Bluetooth App funciona em Android e iOS com BLE. Não é necessário fazer pareamento manual.

  • Abra o DIYables Bluetooth App.
  • Na primeira abertura, conceda as seguintes permissões:
    • Dispositivos Próximos (Android 12+) / Bluetooth (iOS) — necessário para procurar e conectar a dispositivos Bluetooth
    • Localização (somente Android 11 e anteriores) — exigida pelas versões mais antigas do Android para procurar dispositivos BLE
  • Verifique se o Bluetooth está ativado no seu dispositivo.
  • Toque em Connect na tela inicial. O aplicativo vai procurar dispositivos BLE.
DIYables Bluetooth App - Tela Inicial com Botão de Busca
  • Toque em "DIYables Multi-App" nos resultados da busca.
  • Depois de conectar, a tela inicial exibe todos os widgets de aplicativos disponíveis. Os 9 widgets inicializados no sketch do Arduino vão responder e funcionar — os outros widgets na tela inicial vão aparecer, mas não vão funcionar com este sketch.
DIYables Bluetooth App - Tela Inicial com Vários Aplicativos

Toque no ícone de configurações na tela inicial para mostrar ou ocultar aplicativos. Veja o Manual do Usuário do DIYables Bluetooth App para mais detalhes.

  • Abra qualquer um dos widgets a seguir para interagir com o Arduino: Monitor, Chat, Slider, Joystick, Temperature, Plotter, Table, Analog Gauge, Rotator.
  • Alterne entre os widgets livremente — todos compartilham a mesma conexão BLE.

Agora volte ao Serial Monitor na Arduino IDE. Você verá:

∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Nano ESP32
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Nano ESP32' on 'COM15')
New Line
9600 baud
Bluetooth connected! Monitor: System running, uptime: 5s Chat message: Hello Slider value: 128 Joystick: X=0.50, Y=-0.30 Temperature: 22.50 °C
Ln 11, Col 1
Arduino Nano ESP32 on COM15
2

Como Funciona

Inicialização dos Aplicativos

Cada widget é criado com sua própria configuração e seus próprios callbacks:

// All apps share the same Bluetooth server DIYables_BluetoothServer bluetoothServer(bluetooth); // Create individual apps DIYables_BluetoothMonitor bluetoothMonitor(bluetoothServer); DIYables_BluetoothChat bluetoothChat(bluetoothServer); DIYables_BluetoothSlider bluetoothSlider(bluetoothServer, 0, 255, 1); DIYables_BluetoothJoystick bluetoothJoystick(bluetoothServer, false, 5); DIYables_BluetoothTemperature bluetoothTemp(bluetoothServer, -10.0, 50.0, "°C"); DIYables_BluetoothPlotter bluetoothPlotter(bluetoothServer); DIYables_BluetoothTable bluetoothTable(bluetoothServer); DIYables_BluetoothAnalogGauge bluetoothGauge(bluetoothServer, 0.0, 100.0, "%"); DIYables_BluetoothRotator bluetoothRotator(bluetoothServer, ROTATOR_MODE_CONTINUOUS);

Interação entre Aplicativos

Os aplicativos podem interagir entre si. Quando um widget recebe uma entrada, ele pode atualizar outros widgets:

// Slider updates gauge and table bluetoothSlider.onSliderValue([](int value) { float percent = value * 100.0 / 255.0; bluetoothGauge.send(percent); bluetoothTable.sendValueUpdate("Slider 1", String(value)); }); // Joystick updates table bluetoothJoystick.onJoystickValue([](float x, float y) { bluetoothTable.sendValueUpdate("Joystick X", String(x, 2)); bluetoothTable.sendValueUpdate("Joystick Y", String(y, 2)); }); // Rotator updates table bluetoothRotator.onRotatorAngle([](float angle) { bluetoothTable.sendValueUpdate("Rotator Angle", String(angle, 1) + "°"); });

Temporização das Atualizações

Cada aplicativo tem seu próprio intervalo de atualização para equilibrar a capacidade de resposta com a largura de banda do BLE:

void loop() { bluetoothServer.loop(); unsigned long now = millis(); // Plotter: fastest updates (100ms) if (now - lastPlotterTime >= 100) { ... } // Temperature: every 2 seconds if (now - lastTempTime >= 2000) { ... } // Gauge: every 3 seconds if (now - lastGaugeTime >= 3000) { ... } // Monitor, Table: every 5 seconds if (now - lastMonitorTime >= 5000) { ... } if (now - lastTableTime >= 5000) { ... } }

Estrutura da Tabela

O exemplo cria uma tabela com 10 linhas que mostra os dados de todos os aplicativos:

LinhaRótuloDescrição
0StatusStatus da conexão/execução
1UptimeTempo desde a inicialização
2Slider 1Valor atual do slider
3Slider 2Valor do segundo slider
4Joystick XPosição X do joystick
5Joystick YPosição Y do joystick
6TemperatureTemperatura atual
7Gauge ValuePorcentagem atual do medidor
8Rotator AngleÂngulo de rotação atual
9MessagesContagem de mensagens do chat

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

Adicionar ou Remover Widgets

Inclua apenas os widgets necessários para o seu projeto:

// Minimal setup: just Monitor and Slider DIYables_BluetoothMonitor bluetoothMonitor(bluetoothServer); DIYables_BluetoothSlider bluetoothSlider(bluetoothServer, 0, 100, 1); // That's it! The app will only show these two

Lógica Personalizada entre Aplicativos

// Example: Temperature alarm via Monitor void checkTemperatureAlarm(float temp) { if (temp > 40.0) { bluetoothMonitor.send("⚠️ HIGH TEMP ALERT: " + String(temp, 1) + "°C"); bluetoothChat.send("Temperature alarm triggered!"); } }

Solução de Problemas

Problemas Comuns

1. Dispositivo não aparece no aplicativo

  • Confirme que a placa está ligada e que o sketch foi carregado
  • Verifique se o Bluetooth está ativado no seu celular
  • No Android 11 e anteriores, ative também os serviços de localização

2. Alguns widgets não aparecem no menu

  • Todos os widgets inicializados vão aparecer automaticamente
  • Verifique se cada objeto de widget foi criado corretamente
  • O aplicativo descobre os widgets disponíveis a partir do Arduino

3. As atualizações parecem lentas

  • Cada widget tem intervalos de atualização diferentes por design
  • A largura de banda do BLE é limitada; atualizações rápidas demais podem causar congestionamento
  • Reduza a frequência de atualização dos widgets que não precisam de dados em tempo real

4. As atualizações entre widgets não funcionam

  • Verifique se as funções de callback estão registradas corretamente
  • Verifique se os nomes das linhas da tabela coincidem exatamente (diferencia maiúsculas de minúsculas)
  • Confirme que o objeto do widget de destino está acessível dentro do escopo do callback

5. Problemas de memória ou travamentos

  • Executar 9 widgets usa bastante memória
  • Remova os widgets não usados para liberar recursos
  • Reduza o número de linhas da tabela, se necessário

6. O upload falha ou a placa não é reconhecida

  • Instale o pacote de placa Arduino Nano ESP32 mais recente pelo Board Manager
  • Tente outro cabo ou outra porta USB

Ideias de Projetos

  • Painel IoT completo
  • Painel de controle de robô (joystick + monitor + sliders)
  • Estação meteorológica (temperatura + medidor + plotter + tabela)
  • Central de automação residencial (sliders + pinos + monitor + chat)
  • Plataforma de aprendizado STEM (todos os aplicativos para experimentação)

Próximos Passos

Depois de concluir o exemplo do Multiple Apps, explore cada tutorial individual para entender melhor:

  1. Bluetooth Chat — Detalhes sobre mensagens
  2. Bluetooth Slider — Detalhes sobre controle de valores
  3. Bluetooth Plotter — Detalhes sobre visualização de dados
  4. Bluetooth RTC — Sincronização de horário usando o RTC de hardware embutido

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!