Exemplo de Plotter Bluetooth com Arduino UNO R4 WiFi - Tutorial de Visualização de Dados em Tempo Real via BLE

Visão Geral

O exemplo de Plotter Bluetooth transmite dados em tempo real para o app DIYables Bluetooth STEM, para visualização ao vivo. Feito para o Arduino UNO R4 WiFi usando BLE (Bluetooth Low Energy) para exibir leituras de sensores, formas de onda e dados multicanal como gráficos em tempo real no seu smartphone. Ideal para registro de dados, análise de sinais, calibração de sensores e experimentos de ciências.

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 Plotter Bluetooth com Arduino UNO R4 WiFi - Tutorial de Visualização de Dados em Tempo Real via BLE

Recursos

  • Gráfico Multicanal: até 6 canais de dados ao mesmo tempo
  • Eixos Configuráveis: títulos, rótulos e faixa do eixo Y personalizados
  • Rótulos de Legenda: dê um nome a cada canal de dados para ficar mais claro
  • Limite de Amostras: defina o máximo de amostras exibidas
  • Transmissão Rápida: até 10 atualizações por segundo (intervalo de 100ms)
  • Funciona no Android e no iOS: o BLE é suportado nas duas plataformas
  • Sem Necessidade de Pareamento: o BLE conecta automaticamente, sem pareamento manual

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_Plotter para abrir o exemplo, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - Bluetooth Plotter Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Plotter feature: * - Real-time data plotting via Bluetooth * - Plot multiple data series simultaneously * - Configurable plot settings * * 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 the plot * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothPlotter.h> #include <platforms/DIYables_ArduinoBLE.h> // BLE Configuration const char* DEVICE_NAME = "Arduino_Plotter"; 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 Plotter app instance DIYables_BluetoothPlotter bluetoothPlotter; // Variables for generating sample data unsigned long lastPlotTime = 0; const unsigned long PLOT_INTERVAL = 100; // Plot every 100ms float phase = 0; void setup() { Serial.begin(9600); while (!Serial); Serial.println("DIYables Bluetooth - Plotter Example"); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add plotter app to server bluetoothServer.addApp(&bluetoothPlotter); // Configure plotter settings bluetoothPlotter.setPlotTitle("Sensor Data"); bluetoothPlotter.setAxisLabels("Time", "Value"); bluetoothPlotter.setYAxisRange(-15, 30); // Fixed range bluetoothPlotter.setMaxSamples(100); // Show last 100 samples bluetoothPlotter.setLegendLabels("Sine", "Cosine", "Tangent"); // Custom legend labels // Uncomment to enable auto-scaling instead of fixed range: // bluetoothPlotter.enableAutoScale(true); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Optional: Handle requests for current plot data (when app loads) bluetoothPlotter.onDataRequest([]() { // Send initial data when app requests it Serial.println("App requested plot data"); // Could send recent historical data here if needed }); Serial.println("Waiting for Bluetooth connection..."); } void loop() { // Handle Bluetooth server communications bluetoothServer.loop(); // Send plot data at regular intervals if (millis() - lastPlotTime >= PLOT_INTERVAL) { lastPlotTime = millis(); // Generate sample data (sine and cosine waves) float sine = sin(phase); float cosine = cos(phase); float tangent = tan(phase) * 0.3; // Scaled down // Send data to Bluetooth plotter (multiple series) // You can send 1 to 4 values, or use array for more bluetoothPlotter.send(sine, cosine, tangent); // Also print to Serial for Arduino IDE Serial Plotter comparison // Format: value1 value2 value3 (space-separated for Serial Plotter) Serial.print(sine, 2); Serial.print(" "); Serial.print(cosine, 2); Serial.print(" "); Serial.println(tangent, 2); // Alternative methods: // bluetoothPlotter.send(sine); // Single value // bluetoothPlotter.send(sine, cosine); // Two values // float values[] = {sine, cosine, tangent}; // bluetoothPlotter.send(values, 3); // Array of values phase += 0.1; if (phase > 2 * PI) { phase = 0; } // TODO: Replace sample data with your actual sensor readings // Examples: // - Temperature sensor: bluetoothPlotter.send(temperature); // - Accelerometer: bluetoothPlotter.send(accelX, accelY, accelZ); // - Multiple sensors: bluetoothPlotter.send(sensor1, sensor2, sensor3); } 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 - Plotter 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_Plotter" nos resultados da busca para conectar.
  • Depois de conectado, o app volta automaticamente para a tela inicial. Selecione o app Plotter no menu de apps.
DIYables Bluetooth App - Home Screen with Plotter 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á um gráfico em tempo real das formas de onda de Seno, Cosseno e Tangente
DIYables Bluetooth App - Plotter 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! Sending plot data... Sine: 0.00, Cosine: 10.00, Tangent: 0.00
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2

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

Configurar a Aparência do Gráfico

// Set plot title bluetoothPlotter.setPlotTitle("My Sensor Data"); // Set axis labels bluetoothPlotter.setAxisLabels("Time", "Value"); // Set Y-axis range bluetoothPlotter.setYAxisRange(-100, 100); // Set maximum samples to display bluetoothPlotter.setMaxSamples(200); // Set legend labels for each channel bluetoothPlotter.setLegendLabels("Temperature", "Humidity", "Pressure");

Enviar Pontos de Dados

// Send a single value bluetoothPlotter.send(sensorValue); // Send two values bluetoothPlotter.send(temperature, humidity); // Send three values bluetoothPlotter.send(value1, value2, value3); // Send up to six values bluetoothPlotter.send(ch1, ch2, ch3, ch4, ch5, ch6);

Tratar a Solicitação de Dados

bluetoothPlotter.onDataRequest([]() { Serial.println("App requested data"); // App just connected or needs initial config });

Exemplos de Programação

Registrador de Temperatura e Umidade

DIYables_BluetoothPlotter bluetoothPlotter(bluetoothServer); void setup() { bluetoothPlotter.setPlotTitle("Environment Monitor"); bluetoothPlotter.setAxisLabels("Time", "Value"); bluetoothPlotter.setYAxisRange(0, 100); bluetoothPlotter.setMaxSamples(100); bluetoothPlotter.setLegendLabels("Temp (°C)", "Humidity (%)"); } void loop() { bluetoothServer.loop(); static unsigned long lastTime = 0; if (millis() - lastTime >= 1000) { lastTime = millis(); float temp = readTemperature(); float humidity = readHumidity(); bluetoothPlotter.send(temp, humidity); } }

Plotter de Entradas Analógicas

void loop() { bluetoothServer.loop(); static unsigned long lastTime = 0; if (millis() - lastTime >= 100) { lastTime = millis(); int a0 = analogRead(A0); int a1 = analogRead(A1); int a2 = analogRead(A2); bluetoothPlotter.send(a0, a1, a2); } }

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. O gráfico não atualiza

  • Confirme que os dados estão sendo enviados na função loop()
  • Verifique se bluetoothServer.loop() está sendo chamado
  • Garanta que o app está na tela do Plotter

3. Os dados parecem errados ou com ruído

  • Verifique a ligação e as leituras do sensor
  • Confirme que a faixa do eixo Y corresponde à faixa dos seus dados
  • Considere adicionar suavização/filtragem dos dados

4. O título ou os rótulos do gráfico não aparecem

  • Defina a configuração do gráfico em setup() antes de conectar
  • Garanta que o callback onDataRequest reenvie a configuração, se necessário

5. 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

  • Monitoramento ambiental (temperatura, umidade, pressão)
  • Visualização de dados de acelerômetro/giroscópio
  • Ferramenta de calibração de sensores analógicos
  • Análise e comparação de sinais
  • Registrador de dados para experimentos de ciências

Próximos Passos

Depois de dominar o exemplo de Plotter Bluetooth, experimente:

  1. Bluetooth Table - Para exibir dados estruturados
  2. Bluetooth Monitor - Para exibir dados em texto
  3. Bluetooth Temperature - Para exibir a temperatura em estilo de medidor
  4. Multiple Bluetooth Apps - Combinando o plotter 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!