Exemplo de Slider Bluetooth com ESP32 - Tutorial de Interface de Controle com Dois Sliders

Visão Geral

O exemplo Bluetooth Slider oferece dois controles de slider independentes, acessíveis pelo app DIYables Bluetooth STEM. Projetado para placas ESP32, com suporte a conexões BLE (Bluetooth Low Energy) e Bluetooth Clássico. Cada slider oferece valores de 0 a 100, o que os torna perfeitos para controle de PWM, ajuste de brilho, controle de velocidade de motor e qualquer aplicação que precise de valores de controle do tipo analógico.

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 Slider Bluetooth com ESP32 - Tutorial de Interface de Controle com Dois Sliders

Recursos

  • Sliders Duplos: Dois controles de slider independentes (faixa de 0 a 100 cada)
  • Valores em Tempo Real: Atualizações instantâneas de valores via comunicação Bluetooth
  • Compatível com PWM: Valores (0-100) facilmente mapeados para funções analogWrite()
  • Feedback Visual: Exibição em tempo real do valor de cada slider no app
  • 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
  • Faixa e Passo Configuráveis: Personalize a faixa e o tamanho do passo do slider em tempo de execução

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_Slider, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - ESP32 Classic Bluetooth Slider 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 Slider feature: * - Control values using sliders (0-100) * - Support for dual sliders * - Configurable range and step * * 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 control sliders * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothSlider.h> #include <platforms/DIYables_Esp32Bluetooth.h> // Create Bluetooth instances DIYables_Esp32Bluetooth bluetooth("ESP32_Slider"); 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 = 16; const int PWM_PIN_2 = 17; // ESP32 LEDC PWM channels const int PWM_CHANNEL_1 = 0; const int PWM_CHANNEL_2 = 1; void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 Slider Example"); // Initialize PWM using ESP32 LEDC ledcSetup(PWM_CHANNEL_1, 5000, 8); // 5kHz, 8-bit resolution ledcSetup(PWM_CHANNEL_2, 5000, 8); ledcAttachPin(PWM_PIN_1, PWM_CHANNEL_1); ledcAttachPin(PWM_PIN_2, PWM_CHANNEL_2); // 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 using ESP32 LEDC ledcWrite(PWM_CHANNEL_1, pwm1); ledcWrite(PWM_CHANNEL_2, pwm2); // TODO: Add your control logic here based on slider values // Examples: // - Servo control: myServo.write(map(slider1, 0, 100, 0, 180)); // - Motor speed: ledcWrite(MOTOR_CHANNEL, 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(); 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 Slider 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_Slider, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - ESP32 BLE 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: * - 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 control sliders * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothSlider.h> #include <platforms/DIYables_Esp32BLE.h> // BLE Configuration const char* DEVICE_NAME = "ESP32BLE_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_Esp32BLE 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 const int PWM_PIN_1 = 16; const int PWM_PIN_2 = 17; void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 BLE 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!"); bluetoothSlider.send(currentSlider1, currentSlider2); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Set up slider callback for value changes 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 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); analogWrite(PWM_PIN_1, pwm1); analogWrite(PWM_PIN_2, pwm2); // TODO: Add your control logic here }); bluetoothSlider.onGetConfig([]() { bluetoothSlider.send(currentSlider1, currentSlider2); Serial.print("App requested values - Sent: Slider1="); Serial.print(currentSlider1); Serial.print(", Slider2="); Serial.println(currentSlider2); }); Serial.println("Waiting for Bluetooth connection..."); } void loop() { bluetoothServer.loop(); 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 Slider 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_Slider" 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_Slider"
    • Para BLE: toque em "ESP32BLE_Slider"
  • Depois de conectado, o app volta automaticamente para a tela inicial. Selecione o app Slider no menu de apps.
App DIYables Bluetooth - Tela Inicial com o App Slider

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.

  • Mova os dois sliders para controlar os valores de PWM (0-100)
App DIYables Bluetooth - Tela do Slider

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! Slider 1: 50, Slider 2: 30 Slider 1: 75, Slider 2: 30 Slider 1: 75, Slider 2: 60 Slider 1: 100, Slider 2: 85
Ln 11, Col 1
ESP32 Dev Module on COM15
2
  • Mova os sliders no app e observe o feedback em tempo real no Serial Monitor

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

Defina os Valores Padrão dos Sliders

Configure as posições iniciais dos sliders:

// Current slider values (0-100) int currentSlider1 = 25; // Default 25% int currentSlider2 = 50; // Default 50%

Personalize a Faixa e o Passo do Slider

// Create Slider app instance with custom range (min=0, max=255, step=5) DIYables_BluetoothSlider bluetoothSlider(0, 255, 5); // Or change at runtime: bluetoothSlider.setRange(0, 255); // Change range to 0-255 bluetoothSlider.setStep(5); // Change step to 5 (coarser control) // Read current configuration: int currentMin = bluetoothSlider.getMin(); // Get current minimum value int currentMax = bluetoothSlider.getMax(); // Get current maximum value int currentStep = bluetoothSlider.getStep(); // Get current step value

Tratar a Solicitação de Configuração do App

Quando o app se conecta e abre a tela do Slider, ele solicita a configuração dos sliders ao ESP32. Você pode usar o callback onGetConfig() para enviar os valores atuais dos sliders ao app naquele momento:

bluetoothSlider.onGetConfig([]() { // This is called when the app requests slider configuration // Send current slider values so the app displays them correctly bluetoothSlider.send(currentSlider1, currentSlider2); Serial.println("App requested config - sent current values"); });

Enviar Valores para o App

Você pode enviar os valores dos sliders do ESP32 para o app (por exemplo, para atualizar as posições dos sliders no app):

// Send both slider values to the app bluetoothSlider.send(currentSlider1, currentSlider2); // Send a single value (applied to both sliders) bluetoothSlider.send(50);

Tratar Eventos de Conexão

Você pode detectar quando o app se conecta ou se desconecta do ESP32:

// Called when the app connects to ESP32 bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); // Send current slider values to the app bluetoothSlider.send(currentSlider1, currentSlider2); }); // Called when the app disconnects from ESP32 bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); // Optional: stop motors, reset outputs, etc. }); // Check connection status anywhere in your code if (bluetoothServer.isConnected()) { // Do something only when connected }

Como Usar os Sliders

Controles da Interface do App

A interface de sliders no app DIYables Bluetooth oferece:

  • Slider 1: Primeiro slider de controle, com exibição do valor
  • Slider 2: Segundo slider de controle, com exibição do valor
  • Exibição de Valores: Valores numéricos em tempo real dos dois sliders

Faixas de Valores

Cada slider oferece:

  • Faixa Padrão: 0 a 100
  • Configurável: A faixa e o passo podem ser personalizados no código
  • Mapeamento para PWM: Fácil mapeamento para 0-255 em analogWrite()

Exemplos de Programação

Tratador Básico de Slider

void setup() { // Set up slider callback for value changes bluetoothSlider.onSliderValue([](int slider1, int slider2) { // Store the received values currentSlider1 = slider1; currentSlider2 = slider2; // Print slider values Serial.println("Slider 1: " + String(slider1) + ", Slider 2: " + String(slider2)); // Add your control logic here }); }

Controle de Brilho de LED (Exemplo BLE)

// PWM output pins const int PWM_PIN_1 = 16; const int PWM_PIN_2 = 17; void setup() { // Configure PWM pins as outputs pinMode(PWM_PIN_1, OUTPUT); pinMode(PWM_PIN_2, OUTPUT); bluetoothSlider.onSliderValue([](int slider1, int slider2) { currentSlider1 = slider1; currentSlider2 = 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); Serial.println("LED1 Brightness: " + String(pwm1) + ", LED2 Brightness: " + String(pwm2)); }); }

Controle de Brilho de LED (Bluetooth Clássico com LEDC do ESP32)

// PWM output pins const int PWM_PIN_1 = 16; const int PWM_PIN_2 = 17; // ESP32 LEDC PWM channels const int PWM_CHANNEL_1 = 0; const int PWM_CHANNEL_2 = 1; void setup() { // Initialize PWM using ESP32 LEDC ledcSetup(PWM_CHANNEL_1, 5000, 8); // 5kHz, 8-bit resolution ledcSetup(PWM_CHANNEL_2, 5000, 8); ledcAttachPin(PWM_PIN_1, PWM_CHANNEL_1); ledcAttachPin(PWM_PIN_2, PWM_CHANNEL_2); bluetoothSlider.onSliderValue([](int slider1, int slider2) { currentSlider1 = slider1; currentSlider2 = 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 using ESP32 LEDC ledcWrite(PWM_CHANNEL_1, pwm1); ledcWrite(PWM_CHANNEL_2, pwm2); Serial.println("LED1 Brightness: " + String(pwm1) + ", LED2 Brightness: " + String(pwm2)); }); }

Controle de Posição de Servo

#include <ESP32Servo.h> Servo servo1, servo2; void setup() { // Attach servos to pins servo1.attach(16); servo2.attach(17); bluetoothSlider.onSliderValue([](int slider1, int slider2) { currentSlider1 = slider1; currentSlider2 = slider2; // Map slider values (0-100) to servo angles (0-180°) int angle1 = map(slider1, 0, 100, 0, 180); int angle2 = map(slider2, 0, 100, 0, 180); // Move servos to calculated positions servo1.write(angle1); servo2.write(angle2); Serial.println("Servo1: " + String(angle1) + "°, Servo2: " + String(angle2) + "°"); }); }

Controle de Velocidade de Motor

// Motor driver pins const int MOTOR1_PWM = 16; // Motor 1 speed control const int MOTOR1_DIR1 = 18; // Motor 1 direction pin 1 const int MOTOR1_DIR2 = 19; // Motor 1 direction pin 2 const int MOTOR2_PWM = 17; // Motor 2 speed control const int MOTOR2_DIR1 = 21; // Motor 2 direction pin 1 const int MOTOR2_DIR2 = 22; // Motor 2 direction pin 2 void setup() { // Configure motor pins pinMode(MOTOR1_PWM, OUTPUT); pinMode(MOTOR1_DIR1, OUTPUT); pinMode(MOTOR1_DIR2, OUTPUT); pinMode(MOTOR2_PWM, OUTPUT); pinMode(MOTOR2_DIR1, OUTPUT); pinMode(MOTOR2_DIR2, OUTPUT); // Set initial motor directions (forward) digitalWrite(MOTOR1_DIR1, HIGH); digitalWrite(MOTOR1_DIR2, LOW); digitalWrite(MOTOR2_DIR1, HIGH); digitalWrite(MOTOR2_DIR2, LOW); bluetoothSlider.onSliderValue([](int slider1, int slider2) { currentSlider1 = slider1; currentSlider2 = 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 motor speeds analogWrite(MOTOR1_PWM, pwm1); analogWrite(MOTOR2_PWM, pwm2); Serial.println("Motor1: " + String(slider1) + "%, " + "Motor2: " + String(slider2) + "%"); }); }

Controle de Cor de LED RGB

// RGB LED pins const int RED_PIN = 16; const int GREEN_PIN = 17; const int BLUE_PIN = 18; void setup() { pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); bluetoothSlider.onSliderValue([](int slider1, int slider2) { currentSlider1 = slider1; currentSlider2 = slider2; // Use sliders to control RGB components // Slider 1 controls red intensity // Slider 2 controls blue intensity // Green is calculated based on both sliders int redValue = map(slider1, 0, 100, 0, 255); int blueValue = map(slider2, 0, 100, 0, 255); int greenValue = (redValue + blueValue) / 2; analogWrite(RED_PIN, redValue); analogWrite(GREEN_PIN, greenValue); analogWrite(BLUE_PIN, blueValue); Serial.println("RGB - R:" + String(redValue) + " G:" + String(greenValue) + " B:" + String(blueValue)); }); }

Técnicas Avançadas de Programação

Suavização de Valores

class SliderSmoother { private: int currentValue = 0; int targetValue = 0; unsigned long lastUpdate = 0; const int SMOOTH_RATE = 2; // Change per update cycle public: void setTarget(int target) { targetValue = target; } int getCurrentValue() { return currentValue; } bool update() { if (millis() - lastUpdate > 10) { // Update every 10ms bool changed = false; if (currentValue < targetValue) { currentValue = min(currentValue + SMOOTH_RATE, targetValue); changed = true; } else if (currentValue > targetValue) { currentValue = max(currentValue - SMOOTH_RATE, targetValue); changed = true; } lastUpdate = millis(); return changed; } return false; } }; SliderSmoother smoother1, smoother2; void setup() { bluetoothSlider.onSliderValue([](int slider1, int slider2) { // Set target values for smooth transition smoother1.setTarget(slider1); smoother2.setTarget(slider2); }); } void loop() { bluetoothServer.loop(); // Update smoothed values bool changed1 = smoother1.update(); bool changed2 = smoother2.update(); if (changed1 || changed2) { // Map smoothed values (0-100) to PWM (0-255) and apply analogWrite(16, map(smoother1.getCurrentValue(), 0, 100, 0, 255)); analogWrite(17, map(smoother2.getCurrentValue(), 0, 100, 0, 255)); } }

Controle Baseado em Limiar

void setupThresholdControl() { bluetoothSlider.onSliderValue([](int slider1, int slider2) { currentSlider1 = slider1; currentSlider2 = slider2; // Threshold-based control for discrete outputs const int LOW_THRESHOLD = 33; const int MEDIUM_THRESHOLD = 66; // Control digital outputs based on slider 1 thresholds if (slider1 < LOW_THRESHOLD) { // Low level: Turn off all outputs digitalWrite(18, LOW); digitalWrite(19, LOW); digitalWrite(21, LOW); } else if (slider1 < MEDIUM_THRESHOLD) { // Medium level: Turn on first output digitalWrite(18, HIGH); digitalWrite(19, LOW); digitalWrite(21, LOW); } else { // High level: Turn on all outputs digitalWrite(18, HIGH); digitalWrite(19, HIGH); digitalWrite(21, HIGH); } // Use slider 2 for analog PWM control analogWrite(16, map(slider2, 0, 100, 0, 255)); }); }

Sistema de Valores Predefinidos

// Predefined preset values (0-100 range) const int PRESETS[][2] = { {0, 0}, // Preset 0: Both off {25, 50}, // Preset 1: Low/Medium {50, 50}, // Preset 2: Both medium {100, 50}, // Preset 3: High/Medium {100, 100} // Preset 4: Both maximum }; void applyPreset(int presetNumber) { if (presetNumber >= 0 && presetNumber < 5) { currentSlider1 = PRESETS[presetNumber][0]; currentSlider2 = PRESETS[presetNumber][1]; // Update hardware analogWrite(16, map(currentSlider1, 0, 100, 0, 255)); analogWrite(17, map(currentSlider2, 0, 100, 0, 255)); // Send updated values to the app bluetoothSlider.send(currentSlider1, currentSlider2); Serial.println("Applied preset " + String(presetNumber) + ": " + String(currentSlider1) + ", " + String(currentSlider2)); } }

Exemplos de Integração de Hardware

Controle de Fita LED

// For WS2812B or similar addressable LED strips // (requires additional libraries like FastLED or Adafruit NeoPixel) const int LED_STRIP_PIN = 16; const int NUM_LEDS = 30; void setupLEDStrip() { // Initialize LED strip (depends on library used) bluetoothSlider.onSliderValue([](int slider1, int slider2) { currentSlider1 = slider1; currentSlider2 = slider2; // Slider 1 controls brightness (0-100 mapped to 0-255) // Slider 2 controls color temperature or hue (0-100 mapped to 0-255) uint8_t brightness = map(slider1, 0, 100, 0, 255); uint8_t hue = map(slider2, 0, 100, 0, 255); // Update LED strip (example with conceptual functions) // strip.setBrightness(brightness); // strip.fill(CHSV(hue, 255, 255)); // strip.show(); Serial.println("LED Strip - Brightness: " + String(brightness) + ", Hue: " + String(hue)); }); }

Controle de Velocidade de Ventilador

const int FAN1_PIN = 16; const int FAN2_PIN = 17; void setupFanControl() { pinMode(FAN1_PIN, OUTPUT); pinMode(FAN2_PIN, OUTPUT); bluetoothSlider.onSliderValue([](int slider1, int slider2) { currentSlider1 = slider1; currentSlider2 = slider2; // Map slider values (0-100) to PWM (0-255) int pwm1 = map(slider1, 0, 100, 0, 255); int pwm2 = map(slider2, 0, 100, 0, 255); // Control fan speeds with minimum threshold for startup int fan1Speed = (pwm1 > 50) ? map(pwm1, 50, 255, 100, 255) : 0; int fan2Speed = (pwm2 > 50) ? map(pwm2, 50, 255, 100, 255) : 0; analogWrite(FAN1_PIN, fan1Speed); analogWrite(FAN2_PIN, fan2Speed); Serial.println("Fan1: " + String(slider1) + "%, " + "Fan2: " + String(slider2) + "%"); }); }

BLE vs Bluetooth Clássico - Qual Escolher?

RecursoBLE (Esp32BLE_Slider)Bluetooth Clássico (Esp32Bluetooth_Slider)
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-slider */ /* * DIYables Bluetooth Library - ESP32 Classic Bluetooth Slider 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 Slider feature: * - Control values using sliders (0-100) * - Support for dual sliders * - Configurable range and step * * 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 control sliders * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothSlider.h> #include <platforms/DIYables_Esp32Bluetooth.h> #include <ESP32Servo.h> Servo servo1, servo2; // Create Bluetooth instances DIYables_Esp32Bluetooth bluetooth("ESP32_Slider"); 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; void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 Slider Example"); servo1.attach(26); servo2.attach(27); // 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) { currentSlider1 = slider1; currentSlider2 = slider2; // Map slider values (0-100) to servo angles (0-180°) int angle1 = map(slider1, 0, 100, 0, 180); int angle2 = map(slider2, 0, 100, 0, 180); // Move servos to calculated positions servo1.write(angle1); servo2.write(angle2); Serial.println("Servo1: " + String(angle1) + "°, Servo2: " + String(angle2) + "°"); }); // TODO: Add your control logic here based on slider values // Examples: // - Servo control: myServo.write(map(slider1, 0, 100, 0, 180)); // - Motor speed: ledcWrite(MOTOR_CHANNEL, 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(); 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. Os sliders não respondem

  • Verifique o status da conexão Bluetooth no app
  • Confirme a conexão no Serial Monitor
  • Tente desconectar e reconectar

3. Os valores não alcançam a faixa completa

  • Verifique a configuração da faixa do slider: DIYables_BluetoothSlider(min, max, step)
  • Confirme o mapeamento de valores na função de callback
  • Verifique no Serial Monitor os valores realmente recebidos

4. 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
  • Verifique no Serial Monitor as mensagens de desconexão/reconexão

5. A saída PWM não funciona

  • Verifique se os pinos oferecem suporte a PWM na sua variante de ESP32
  • Para o ESP32: use ledcSetup/ledcAttachPin/ledcWrite para PWM por hardware
  • Verifique as conexões de hardware e os requisitos da carga

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 debugSliderValues(int slider1, int slider2) { Serial.println("=== Slider Debug ==="); Serial.println("Slider 1: " + String(slider1) + "%"); Serial.println("Slider 2: " + String(slider2) + "%"); Serial.println("PWM 1: " + String(map(slider1, 0, 100, 0, 255))); Serial.println("PWM 2: " + String(map(slider2, 0, 100, 0, 255))); Serial.println("==================="); }

Ideias de Projetos

Projetos de Controle de Iluminação

  • Controle de brilho da iluminação de ambientes via Bluetooth
  • Interface de mistura de cores RGB
  • Controle de velocidade de animação de fita LED
  • Controle sem fio de iluminação de palco

Projetos de Controle de Motores

  • Velocidade de robô controlada por Bluetooth
  • Regulagem sem fio da velocidade de ventilador
  • Controle de vazão de bomba
  • Velocidade de esteira transportadora

Projetos de Áudio

  • Controle de volume sem fio
  • Controle de tom/equalizador
  • Intensidade de efeitos sonoros

Automação Residencial

  • Controle de clima sem fio (intensidade de aquecimento/resfriamento)
  • Controle de posição de persianas via Bluetooth
  • Controle de vazão de sistema de irrigação

Integração com Outros Apps Bluetooth

Combine com o Bluetooth Joystick

Use sliders para os limites de velocidade e o joystick para a direção:

// Global speed limit from sliders int maxSpeed = 100; // In Bluetooth Slider callback bluetoothSlider.onSliderValue([](int slider1, int slider2) { maxSpeed = slider1; // Use slider 1 as global speed limit }); // In Bluetooth Joystick callback bluetoothJoystick.onJoystickValue([](int x, int y) { // Scale joystick values by slider-controlled speed limit int scaledX = map(x, -100, 100, -maxSpeed, maxSpeed); int scaledY = map(y, -100, 100, -maxSpeed, maxSpeed); controlRobot(scaledX, scaledY); });

Combine com o Bluetooth Digital Pins

Use sliders para controlar o PWM e pinos digitais para ligar/desligar:

bluetoothSlider.onSliderValue([](int slider1, int slider2) { // Only apply PWM if corresponding digital pins are ON if (digitalRead(18) == HIGH) { analogWrite(16, map(slider1, 0, 100, 0, 255)); } else { analogWrite(16, 0); } if (digitalRead(19) == HIGH) { analogWrite(17, map(slider2, 0, 100, 0, 255)); } else { analogWrite(17, 0); } });

Próximos Passos

Depois de dominar o exemplo Bluetooth Slider, experimente:

  1. Bluetooth Joystick - Para controle direcional 2D
  2. Bluetooth Digital Pins - Para controle discreto de ligar/desligar
  3. Bluetooth Monitor - Para depurar os valores dos sliders
  4. Multiple Bluetooth Apps - Combinando sliders com outros controles

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!