Exemplo de Slider Bluetooth com Arduino UNO R4 WiFi - Tutorial de Controle com Dois Sliders via BLE

Visão Geral

O exemplo de Slider Bluetooth oferece controles com dois sliders, acessíveis pelo app DIYables Bluetooth STEM. Feito para o Arduino UNO R4 WiFi usando BLE (Bluetooth Low Energy) para controlar dois valores independentes, com faixa e passo configuráveis. Perfeito para brilho de LED, velocidade de motor, posicionamento de servo e qualquer aplicação que exija uma entrada numérica ajustável.

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 Slider Bluetooth com Arduino UNO R4 WiFi - Tutorial de Controle com Dois Sliders via BLE

Recursos

  • Dois Sliders: dois controles de slider independentes
  • Faixa Configurável: defina os valores mínimo, máximo e de passo
  • Atualizações em Tempo Real: os valores dos sliders são enviados na hora em que mudam
  • Pronto para PWM: mapeie os valores dos sliders diretamente para a saída PWM
  • 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_Slider para abrir o exemplo, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - Bluetooth Slider Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Slider feature: * - Control values using sliders (0-100) * - Support for dual sliders * - Configurable range and step * * 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 control sliders * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothSlider.h> #include <platforms/DIYables_ArduinoBLE.h> // BLE Configuration const char* DEVICE_NAME = "Arduino_Slider"; 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 Slider app instance (min=0, max=100, step=1) DIYables_BluetoothSlider bluetoothSlider(0, 100, 1); // Variables to store current slider values int currentSlider1 = 0; int currentSlider2 = 0; // PWM output pins (for LED brightness control example) const int PWM_PIN_1 = 9; const int PWM_PIN_2 = 10; void setup() { Serial.begin(9600); while (!Serial); Serial.println("DIYables Bluetooth - Slider Example"); // Initialize PWM pins pinMode(PWM_PIN_1, OUTPUT); pinMode(PWM_PIN_2, OUTPUT); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add slider app to server bluetoothServer.addApp(&bluetoothSlider); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); // Send initial slider positions bluetoothSlider.send(currentSlider1, currentSlider2); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Set up slider callback for value changes bluetoothSlider.onSliderValue([](int slider1, int slider2) { // Store the received values currentSlider1 = slider1; currentSlider2 = slider2; // Print slider values (0-100) Serial.print("Slider 1: "); Serial.print(slider1); Serial.print(", Slider 2: "); Serial.println(slider2); // Map slider values (0-100) to PWM range (0-255) int pwm1 = map(slider1, 0, 100, 0, 255); int pwm2 = map(slider2, 0, 100, 0, 255); // Control LED brightness analogWrite(PWM_PIN_1, pwm1); analogWrite(PWM_PIN_2, pwm2); // TODO: Add your control logic here based on slider values // Examples: // - Servo control: servo.write(map(slider1, 0, 100, 0, 180)); // - Motor speed: analogWrite(MOTOR_PIN, pwm1); // - Volume control: setVolume(slider1); // - Brightness control: setBrightness(slider2); }); // Optional: Handle requests for current slider values (when app loads) bluetoothSlider.onGetConfig([]() { // Send the stored slider values back to the app bluetoothSlider.send(currentSlider1, currentSlider2); Serial.print("App requested values - Sent: Slider1="); Serial.print(currentSlider1); Serial.print(", Slider2="); Serial.println(currentSlider2); }); // You can change slider configuration at runtime: // bluetoothSlider.setRange(0, 255); // Change range to 0-255 // bluetoothSlider.setStep(5); // Change step to 5 (coarser control) Serial.println("Waiting for Bluetooth connection..."); } void loop() { // Handle Bluetooth server communications bluetoothServer.loop(); // Optional: Update slider positions based on sensor input // Example: Send current values periodically /* static unsigned long lastUpdate = 0; if (millis() - lastUpdate >= 5000) { lastUpdate = millis(); bluetoothSlider.send(currentSlider1, currentSlider2); } */ 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 - Slider 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_Slider" nos resultados da busca para conectar.
  • Depois de conectado, o app volta automaticamente para a tela inicial. Selecione o app Slider no menu de apps.
DIYables Bluetooth App - Home Screen with Slider 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.

  • Arraste os sliders para mudar os valores
DIYables Bluetooth App - Slider 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! Slider 1: 50, Slider 2: 0 Slider 1: 75, Slider 2: 0 Slider 1: 100, Slider 2: 25
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2
  • Ajuste os sliders e veja os valores mudarem em tempo real no Serial Monitor

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

Configurar a Faixa do Slider

// Constructor: DIYables_BluetoothSlider(min, max, step) DIYables_BluetoothSlider bluetoothSlider(0, 100, 1); // Change range at runtime bluetoothSlider.setRange(0, 255); // Change step size bluetoothSlider.setStep(5); // Coarser control // Read configuration int minVal = bluetoothSlider.getMin(); int maxVal = bluetoothSlider.getMax(); int step = bluetoothSlider.getStep();

Tratar as Mudanças do Slider

bluetoothSlider.onSliderValue([](int slider1, int slider2) { currentSlider1 = slider1; currentSlider2 = slider2; Serial.print("Slider 1: "); Serial.print(slider1); Serial.print(", Slider 2: "); Serial.println(slider2); // Map to PWM and control output int pwm1 = map(slider1, 0, 100, 0, 255); analogWrite(PWM_PIN_1, pwm1); });

Enviar os Valores Atuais ao App

bluetoothSlider.onGetConfig([]() { bluetoothSlider.send(currentSlider1, currentSlider2); }); // Or send anytime: bluetoothSlider.send(50, 75); // Set both sliders

Tratar os Eventos de Conexão

bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); bluetoothSlider.send(currentSlider1, currentSlider2); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); });

Exemplos de Programação

Controle de Brilho de LED

const int LED_PIN_1 = 9; const int LED_PIN_2 = 10; bluetoothSlider.onSliderValue([](int slider1, int slider2) { int brightness1 = map(slider1, 0, 100, 0, 255); int brightness2 = map(slider2, 0, 100, 0, 255); analogWrite(LED_PIN_1, brightness1); analogWrite(LED_PIN_2, brightness2); Serial.print("LED 1: "); Serial.print(brightness1); Serial.print(", LED 2: "); Serial.println(brightness2); });

Controle de Servo

#include <Servo.h> Servo servo1, servo2; void setup() { servo1.attach(9); servo2.attach(10); bluetoothSlider.onSliderValue([](int slider1, int slider2) { int angle1 = map(slider1, 0, 100, 0, 180); int angle2 = map(slider2, 0, 100, 0, 180); servo1.write(angle1); servo2.write(angle2); Serial.print("Servo 1: "); Serial.print(angle1); Serial.print("°, Servo 2: "); Serial.print(angle2); Serial.println("°"); }); }

Velocidade do Motor com Direção

const int MOTOR_SPEED_PIN = 9; const int MOTOR_DIR_PIN = 8; bluetoothSlider.onSliderValue([](int slider1, int slider2) { // Slider 1: speed (0-100%) // Slider 2: direction threshold (below 50 = reverse, above 50 = forward) int speed = map(slider1, 0, 100, 0, 255); bool forward = (slider2 >= 50); analogWrite(MOTOR_SPEED_PIN, speed); digitalWrite(MOTOR_DIR_PIN, forward ? HIGH : LOW); Serial.print("Speed: "); Serial.print(slider1); Serial.print("%, Direction: "); Serial.println(forward ? "Forward" : "Reverse"); });

Técnicas Avançadas de Programação

Slider com Zona Morta

bluetoothSlider.onSliderValue([](int slider1, int slider2) { // Add dead zone around center (45-55 = stop) if (slider1 >= 45 && slider1 <= 55) { Serial.println("Center - stopped"); analogWrite(MOTOR_PIN, 0); } else { int speed = map(slider1, 0, 100, 0, 255); analogWrite(MOTOR_PIN, speed); } });

Limitação de Taxa

unsigned long lastSliderAction = 0; const unsigned long SLIDER_COOLDOWN = 50; // 50ms minimum bluetoothSlider.onSliderValue([](int slider1, int slider2) { if (millis() - lastSliderAction >= SLIDER_COOLDOWN) { lastSliderAction = millis(); // Process slider value analogWrite(PWM_PIN, map(slider1, 0, 100, 0, 255)); } });

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-slider */ /* * DIYables Bluetooth Library - Bluetooth Slider Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Slider feature: * - Control values using sliders (0-100) * - Support for dual sliders * - Configurable range and step * * 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 control sliders * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothSlider.h> #include <platforms/DIYables_ArduinoBLE.h> #include <Servo.h> Servo servo1, servo2; // BLE Configuration const char* DEVICE_NAME = "Arduino_Slider"; 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 Slider app instance (min=0, max=100, step=1) DIYables_BluetoothSlider bluetoothSlider(0, 100, 1); // Variables to store current slider values int currentSlider1 = 0; int currentSlider2 = 0; // // PWM output pins (for LED brightness control example) // const int PWM_PIN_1 = 9; // const int PWM_PIN_2 = 10; void setup() { Serial.begin(9600); while (!Serial); Serial.println("DIYables Bluetooth - Slider Example"); // Initialize PWM pins servo1.attach(3); servo2.attach(5); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add slider app to server bluetoothServer.addApp(&bluetoothSlider); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); // Send initial slider positions bluetoothSlider.send(currentSlider1, currentSlider2); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Set up slider callback for value changes bluetoothSlider.onSliderValue([](int slider1, int slider2) { int angle1 = map(slider1, 0, 100, 0, 180); int angle2 = map(slider2, 0, 100, 0, 180); servo1.write(angle1); servo2.write(angle2); Serial.print("Servo 1: "); Serial.print(angle1); Serial.print("°, Servo 2: "); Serial.print(angle2); Serial.println("°"); }); // Optional: Handle requests for current slider values (when app loads) bluetoothSlider.onGetConfig([]() { // Send the stored slider values back to the app bluetoothSlider.send(currentSlider1, currentSlider2); Serial.print("App requested values - Sent: Slider1="); Serial.print(currentSlider1); Serial.print(", Slider2="); Serial.println(currentSlider2); }); // You can change slider configuration at runtime: // bluetoothSlider.setRange(0, 255); // Change range to 0-255 // bluetoothSlider.setStep(5); // Change step to 5 (coarser control) Serial.println("Waiting for Bluetooth connection..."); } void loop() { // Handle Bluetooth server communications bluetoothServer.loop(); // Optional: Update slider positions based on sensor input // Example: Send current values periodically /* static unsigned long lastUpdate = 0; if (millis() - lastUpdate >= 5000) { lastUpdate = millis(); bluetoothSlider.send(currentSlider1, currentSlider2); } */ 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
  • Tente reiniciar o Bluetooth do seu celular

2. As mudanças do slider não são recebidas

  • Verifique o status da conexão Bluetooth no app
  • Confirme que o callback onSliderValue está configurado corretamente
  • Verifique se há mensagens de erro no Serial Monitor

3. A saída PWM não funciona

  • Confirme que o pino suporta PWM (pinos 3, 5, 6, 9, 10, 11 no UNO R4)
  • Verifique as conexões da ligação
  • Teste primeiro com um sketch simples de analogWrite

4. O slider volta para 0 ao reconectar

  • Implemente o callback onGetConfig para enviar os valores guardados ao reconectar
  • Guarde os valores dos sliders em variáveis que persistam entre as conexões

5. A conexão cai com frequência

  • Aproxime-se do Arduino (reduza a distância)
  • Verifique se há interferência de outros dispositivos BLE
  • 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
  • Pressione o botão de reset da placa antes de fazer o upload

Ideias de Projetos

Controle de Iluminação

  • Controlador de brilho para dois LEDs
  • Misturador de cores para LED RGB (use dois sliders para matiz/saturação)
  • Brilho e temperatura de cor de fita LED
  • Dimmer de iluminação de palco

Controle de Motores

  • Controlador de velocidade de motor DC
  • Posicionamento de dois servos
  • Suporte pan-tilt para câmera
  • Velocidade das rodas de um robô

Áudio

  • Controle de volume
  • Frequência e duração de tons
  • Bandas de equalizador

Próximos Passos

Depois de dominar o exemplo de Slider Bluetooth, experimente:

  1. Bluetooth Joystick - Para controle direcional 2D
  2. Bluetooth Rotator - Para controle angular/rotacional
  3. Bluetooth Temperature - Para exibir a temperatura em um medidor
  4. Multiple Bluetooth Apps - Combinando o slider 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!