Exemplo de Monitor Bluetooth com Arduino UNO R4 WiFi - Tutorial de Monitor Serial Sem Fio via BLE

Visão Geral

O exemplo de Monitor Bluetooth oferece um monitor serial sem fio, acessível pelo app DIYables Bluetooth STEM. Feito para o Arduino UNO R4 WiFi usando BLE (Bluetooth Low Energy) para enviar, sem fio e em tempo real, mensagens de status, saída de depuração e leituras de sensores para o seu smartphone. Ele também recebe comandos de texto enviados pelo app. Perfeito para depuração sem fio, monitoramento remoto e registro de eventos do sistema.

Nota: O Arduino UNO R4 WiFi só suporta BLE (Bluetooth Low Energy). Ele não suporta Bluetooth Clássico. O app DIYables Bluetooth suporta BLE e Bluetooth Clássico no Android, e BLE no iOS. Como esta placa usa BLE, o app funciona no Android e no iOS.

Exemplo de Monitor Bluetooth com Arduino UNO R4 WiFi - Tutorial de Monitor Serial Sem Fio via BLE

Recursos

  • Monitor Serial Sem Fio: envie mensagens de texto para o seu celular
  • Comunicação nos Dois Sentidos: envie comandos do app para o Arduino
  • Transmissão em Tempo Real: saída contínua, como no Serial Monitor
  • Tratamento de Comandos: processe comandos de texto vindos do app
  • Funciona no Android e no iOS: o BLE é suportado nas duas plataformas
  • Sem Necessidade de Pareamento: o BLE conecta automaticamente, sem pareamento manual
  • Baixo Consumo: o BLE consome menos energia que o Bluetooth Clássico

Código Arduino UNO R4 WiFi

Passos Rápidos

Siga estas instruções passo a passo:

  • Se esta é a primeira vez que você usa o Arduino UNO R4 WiFi, consulte o guia de primeiros passos do Arduino UNO R4 WiFi.
  • Conecte a placa Arduino UNO R4 WiFi ao seu computador usando um cabo USB.
  • Abra o Arduino IDE no seu computador.
  • Selecione a placa Arduino UNO R4 WiFi e a porta COM apropriada.
  • Vá até o ícone Libraries na barra lateral esquerda do Arduino IDE.
  • Pesquise "DIYables Bluetooth" e encontre a biblioteca DIYables Bluetooth, da DIYables
  • Clique no botão Install para instalar a biblioteca.
Arduino UNO R4 DIYables Bluetooth library
  • Será pedido que você instale algumas outras dependências da biblioteca
  • Clique no botão Install All para instalar todas as dependências da biblioteca.
Arduino UNO R4 DIYables Bluetooth dependency

Código BLE

  • No Arduino IDE, vá em File Examples DIYables Bluetooth ArduinoBLE_Monitor para abrir o exemplo, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - Bluetooth Monitor Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Monitor feature: * - Send real-time status messages to the mobile app * - Display system information and sensor readings * - Receive and process commands from the app * - Perfect for debugging and system monitoring * * Compatible Boards: * - Arduino UNO R4 WiFi * - Arduino Nano 33 BLE / BLE Sense * - Arduino Nano 33 IoT * - Arduino MKR WiFi 1010 * - Arduino Nano RP2040 Connect * - Any board supporting the ArduinoBLE library * * Setup: * 1. Upload the sketch to your Arduino * 2. Open Serial Monitor to see connection status * 3. Use DIYables Bluetooth App to connect and view monitor output * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothMonitor.h> #include <platforms/DIYables_ArduinoBLE.h> // BLE Configuration const char* DEVICE_NAME = "Arduino_Monitor"; 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_ArduinoBLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Monitor app instance DIYables_BluetoothMonitor bluetoothMonitor; // Variables for demo unsigned long lastUpdate = 0; const unsigned long UPDATE_INTERVAL = 3000; // Send update every 3 seconds int messageCount = 0; bool ledState = false; void setup() { Serial.begin(9600); while (!Serial); Serial.println("DIYables Bluetooth - Monitor Example"); // Initialize built-in LED pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add monitor app to server bluetoothServer.addApp(&bluetoothMonitor); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); bluetoothMonitor.send("=== Arduino Monitor Connected ==="); bluetoothMonitor.send("System Ready"); bluetoothMonitor.send("Type HELP for available commands"); bluetoothMonitor.send(""); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Set up message handler for incoming commands bluetoothMonitor.onMonitorMessage([](const String& message) { Serial.print("Received command: "); Serial.println(message); handleCommand(message); }); Serial.println("Waiting for Bluetooth connection..."); } void handleCommand(const String& cmd) { if (cmd == "HELP") { bluetoothMonitor.send("Available Commands:"); bluetoothMonitor.send(" LED_ON - Turn LED on"); bluetoothMonitor.send(" LED_OFF - Turn LED off"); bluetoothMonitor.send(" STATUS - Show system status"); bluetoothMonitor.send(" CLEAR - Clear monitor (if supported)"); bluetoothMonitor.send(" HELP - Show this help"); } else if (cmd == "LED_ON") { digitalWrite(LED_BUILTIN, HIGH); ledState = true; bluetoothMonitor.send("✓ LED turned ON"); } else if (cmd == "LED_OFF") { digitalWrite(LED_BUILTIN, LOW); ledState = false; bluetoothMonitor.send("✓ LED turned OFF"); } else if (cmd == "STATUS") { showStatus(); } else if (cmd == "CLEAR") { // App should handle clearing the display bluetoothMonitor.send(""); } else { bluetoothMonitor.send("✗ Unknown command: " + cmd); bluetoothMonitor.send("Type HELP for available commands"); } } void showStatus() { bluetoothMonitor.send("=== System Status ==="); // LED Status bluetoothMonitor.send("LED State: " + String(ledState ? "ON" : "OFF")); // Uptime unsigned long uptime = millis() / 1000; bluetoothMonitor.send("Uptime: " + String(uptime / 3600) + "h " + String((uptime % 3600) / 60) + "m " + String(uptime % 60) + "s"); // Free Memory (approximate for AVR) #ifdef __AVR__ extern int __heap_start, *__brkval; int freeMemory = (int) &freeMemory - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); bluetoothMonitor.send("Free Memory: " + String(freeMemory) + " bytes"); #endif // Messages sent bluetoothMonitor.send("Messages Sent: " + String(messageCount)); bluetoothMonitor.send("===================="); } void sendPeriodicUpdate() { messageCount++; // Example of different message types if (messageCount % 3 == 0) { // Send status update bluetoothMonitor.send("[INFO] Heartbeat #" + String(messageCount)); } else if (messageCount % 5 == 0) { // Send simulated sensor reading int sensorValue = random(0, 1024); bluetoothMonitor.send("[SENSOR] Reading: " + String(sensorValue) + " (random demo value)"); } else { // Send timestamp bluetoothMonitor.send("[TIME] Uptime: " + String(millis() / 1000) + "s"); } // Optionally log to Serial as well Serial.print("Sent update #"); Serial.println(messageCount); } void loop() { // Handle Bluetooth server communications bluetoothServer.loop(); // Send periodic updates (only when connected) if (bluetooth.isConnected() && millis() - lastUpdate >= UPDATE_INTERVAL) { lastUpdate = millis(); sendPeriodicUpdate(); } delay(10); }
  • Clique no botão Upload no Arduino IDE para carregar o código no Arduino UNO R4 WiFi
  • Abra o Serial Monitor
  • Veja o resultado no Serial Monitor. Ele deve ficar parecido com o abaixo:
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno R4 WiFi
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno R4 WiFi' on 'COM15')
New Line
9600 baud
DIYables Bluetooth - Monitor Example Waiting for Bluetooth connection...
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2

App para Celular

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

Nota: O app DIYables Bluetooth suporta BLE e Bluetooth Clássico no Android, e BLE no iOS. Como o Arduino UNO R4 WiFi usa BLE, o app funciona no Android e no iOS. Não é preciso pareamento manual para o BLE — basta procurar e conectar.

  • Abra o app DIYables Bluetooth
  • Ao abrir o app pela primeira vez, ele vai pedir permissões. Conceda as seguintes:
    • Permissão de Dispositivos por Perto (Android 12+) / permissão de Bluetooth (iOS) - necessária para procurar e conectar 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.
DIYables Bluetooth App - Home Screen with Scan Button
  • Encontre e toque em "Arduino_Monitor" nos resultados da busca para conectar.
  • Depois de conectado, o app volta automaticamente para a tela inicial. Selecione o app Monitor no menu de apps.
DIYables Bluetooth App - Home Screen with Monitor App

Nota: 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.

  • Você verá mensagens de status chegando na tela do monitor
  • Digite LED_ON no campo de entrada e toque em Send — o LED embutido do Arduino UNO R4 WiFi vai ACENDER, e o monitor vai exibir uma mensagem de confirmação
DIYables Bluetooth App - Monitor Screen

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

∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno R4 WiFi
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno R4 WiFi' on 'COM15')
New Line
9600 baud
Bluetooth connected! Sent update #1 Sent update #2 Sent update #3
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2

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

Enviar Mensagens

// Send text messages to the app bluetoothMonitor.send("System started"); bluetoothMonitor.send("Temperature: " + String(temp, 1) + " °C"); bluetoothMonitor.send("[ERROR] Sensor disconnected!");

Tratar os Comandos Recebidos

Use o callback onMonitorMessage() para receber os comandos digitados no app Monitor e reagir a eles:

bluetoothMonitor.onMonitorMessage([](const String& message) { Serial.print("Received: "); Serial.println(message); if (message == "HELP") { bluetoothMonitor.send("Commands: LED_ON, LED_OFF, STATUS, HELP"); } else if (message == "LED_ON") { digitalWrite(LED_BUILTIN, HIGH); bluetoothMonitor.send("LED turned ON"); } else if (message == "LED_OFF") { digitalWrite(LED_BUILTIN, LOW); bluetoothMonitor.send("LED turned OFF"); } else if (message == "STATUS") { bluetoothMonitor.send("Uptime: " + String(millis() / 1000) + "s"); bluetoothMonitor.send("LED: " + String(digitalRead(LED_BUILTIN) ? "ON" : "OFF")); } else { bluetoothMonitor.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 a leitura de um sensor — qualquer palavra que você digitar no app vira um comando.

Exemplos de Programação

Transmissão do Status de Sensores

void loop() { bluetoothServer.loop(); static unsigned long lastUpdate = 0; if (bluetooth.isConnected() && millis() - lastUpdate >= 3000) { lastUpdate = millis(); int light = analogRead(A0); float voltage = analogRead(A1) * 5.0 / 1023.0; bluetoothMonitor.send("[SENSOR] Light: " + String(map(light, 0, 1023, 0, 100)) + "%"); bluetoothMonitor.send("[SENSOR] Voltage: " + String(voltage, 2) + "V"); bluetoothMonitor.send("[INFO] Uptime: " + String(millis() / 1000) + "s"); } delay(10); }

Registro Baseado em Eventos

const int BUTTON_PIN = 7; int lastButtonState = HIGH; void loop() { bluetoothServer.loop(); int buttonState = digitalRead(BUTTON_PIN); if (buttonState != lastButtonState) { lastButtonState = buttonState; if (buttonState == LOW) { bluetoothMonitor.send("[EVENT] Button pressed!"); } else { bluetoothMonitor.send("[EVENT] Button released"); } } delay(10); }

Tutorial em Vídeo

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

/* * Este código de Arduino UNO R4 foi desenvolvido por pt.newbiely.com * Este código de Arduino UNO R4 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-diyables-bluetooth-app-monitor */ /* * DIYables Bluetooth Library - Bluetooth Monitor Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Monitor feature: * - Send real-time status messages to the mobile app * - Display system information and sensor readings * - Receive and process commands from the app * - Perfect for debugging and system monitoring * * Compatible Boards: * - Arduino UNO R4 WiFi * - Arduino Nano 33 BLE / BLE Sense * - Arduino Nano 33 IoT * - Arduino MKR WiFi 1010 * - Arduino Nano RP2040 Connect * - Any board supporting the ArduinoBLE library * * Setup: * 1. Upload the sketch to your Arduino * 2. Open Serial Monitor to see connection status * 3. Use DIYables Bluetooth App to connect and view monitor output * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothMonitor.h> #include <platforms/DIYables_ArduinoBLE.h> // BLE Configuration const char* DEVICE_NAME = "Arduino_Monitor"; 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_ArduinoBLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Monitor app instance DIYables_BluetoothMonitor bluetoothMonitor; // Variables for demo unsigned long lastUpdate = 0; const unsigned long UPDATE_INTERVAL = 3000; // Send update every 3 seconds int messageCount = 0; bool ledState = false; void setup() { Serial.begin(9600); while (!Serial); Serial.println("DIYables Bluetooth - Monitor Example"); // Initialize built-in LED pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add monitor app to server bluetoothServer.addApp(&bluetoothMonitor); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); bluetoothMonitor.send("=== Arduino Monitor Connected ==="); bluetoothMonitor.send("System Ready"); bluetoothMonitor.send("Type HELP for available commands"); bluetoothMonitor.send(""); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Set up message handler for incoming commands bluetoothMonitor.onMonitorMessage([](const String& message) { Serial.print("Received command: "); Serial.println(message); handleCommand(message); }); Serial.println("Waiting for Bluetooth connection..."); } void handleCommand(const String& cmd) { if (cmd == "HELP") { bluetoothMonitor.send("Available Commands:"); bluetoothMonitor.send(" LED_ON - Turn LED on"); bluetoothMonitor.send(" LED_OFF - Turn LED off"); bluetoothMonitor.send(" STATUS - Show system status"); bluetoothMonitor.send(" CLEAR - Clear monitor (if supported)"); bluetoothMonitor.send(" HELP - Show this help"); } else if (cmd == "LED_ON") { digitalWrite(LED_BUILTIN, HIGH); ledState = true; bluetoothMonitor.send("✓ LED turned ON"); } else if (cmd == "LED_OFF") { digitalWrite(LED_BUILTIN, LOW); ledState = false; bluetoothMonitor.send("✓ LED turned OFF"); } else if (cmd == "STATUS") { showStatus(); } else if (cmd == "CLEAR") { // App should handle clearing the display bluetoothMonitor.send(""); } else { bluetoothMonitor.send("✗ Unknown command: " + cmd); bluetoothMonitor.send("Type HELP for available commands"); } } void showStatus() { bluetoothMonitor.send("=== System Status ==="); // LED Status bluetoothMonitor.send("LED State: " + String(ledState ? "ON" : "OFF")); // Uptime unsigned long uptime = millis() / 1000; bluetoothMonitor.send("Uptime: " + String(uptime / 3600) + "h " + String((uptime % 3600) / 60) + "m " + String(uptime % 60) + "s"); // Free Memory (approximate for AVR) #ifdef __AVR__ extern int __heap_start, *__brkval; int freeMemory = (int) &freeMemory - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); bluetoothMonitor.send("Free Memory: " + String(freeMemory) + " bytes"); #endif // Messages sent bluetoothMonitor.send("Messages Sent: " + String(messageCount)); bluetoothMonitor.send("===================="); } void sendPeriodicUpdate() { messageCount++; // Example of different message types if (messageCount % 3 == 0) { // Send status update bluetoothMonitor.send("[INFO] Heartbeat #" + String(messageCount)); } else if (messageCount % 5 == 0) { // Send simulated sensor reading int sensorValue = random(0, 1024); bluetoothMonitor.send("[SENSOR] Reading: " + String(sensorValue) + " (random demo value)"); } else { // Send timestamp bluetoothMonitor.send("[TIME] Uptime: " + String(millis() / 1000) + "s"); } // Optionally log to Serial as well Serial.print("Sent update #"); Serial.println(messageCount); } void loop() { // Handle Bluetooth server communications bluetoothServer.loop(); // Send periodic updates (only when connected) if (bluetooth.isConnected() && millis() - lastUpdate >= UPDATE_INTERVAL) { lastUpdate = millis(); sendPeriodicUpdate(); } delay(10); }

Solução de Problemas

Problemas Comuns

1. Não consigo encontrar o dispositivo no app

  • Verifique se o Arduino UNO R4 WiFi está ligado e se o sketch foi carregado
  • Verifique se o Bluetooth do seu celular está ativado
  • No Android 11 e anteriores, ative também os serviços de Localização

2. Nenhuma mensagem aparece no app

  • Confirme que bluetoothMonitor.send() está sendo chamado
  • Verifique se bluetoothServer.loop() está no loop principal
  • Confirme a conexão no Serial Monitor

3. As mensagens chegam atrasadas

  • Reduza o intervalo de atualização para ter mensagens mais frequentes
  • Evite enviar mensagens demais e rápido demais (o BLE tem limites de largura de banda)

4. Os comandos do app não são recebidos

  • Confirme que o callback onMonitorMessage está configurado
  • Verifique no Serial Monitor a saída dos comandos recebidos

5. A conexão cai com frequência

  • Aproxime-se do Arduino (reduza a distância)
  • Garanta uma alimentação USB estável

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

  • Instale o pacote de placas Arduino UNO R4 mais recente pelo Board Manager
  • Tente outro cabo ou outra porta USB

Ideias de Projetos

  • Console de depuração sem fio
  • Registrador de dados de sensores
  • Monitor de integridade do sistema
  • Sistema de notificação de eventos
  • Interface de comandos remota

Próximos Passos

Depois de dominar o exemplo de Monitor Bluetooth, experimente:

  1. Bluetooth Chat - Para mensagens interativas nos dois sentidos
  2. Bluetooth Table - Para exibir dados estruturados
  3. Bluetooth Plotter - Para visualização de dados
  4. Multiple Bluetooth Apps - Combinando o monitor com outros apps

Suporte

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