Exemplo Bluetooth Joystick com ESP32 - Tutorial de Interface de Controle 2D Interativa

Visão Geral

O exemplo Bluetooth Joystick oferece um controle de joystick 2D interativo, acessível pelo app DIYables Bluetooth STEM. Projetado para placas ESP32, com suporte a conexões BLE (Bluetooth Low Energy) e Bluetooth Clássico. O joystick envia em tempo real valores de coordenadas X e Y de -100 a +100, o que o torna ideal para controle de robôs, acionamento de motores, posicionamento de servos e qualquer aplicação que exija entrada direcional.

Este exemplo suporta dois modos Bluetooth:

  • ESP32 BLE (Bluetooth Low Energy): Funciona no Android e no iOS
  • ESP32 Bluetooth Clássico: Funciona somente no Android. O iOS não suporta o Bluetooth Clássico. Use o BLE se você precisar de suporte ao iOS.
Exemplo Bluetooth Joystick com ESP32 - Tutorial de Interface de Controle 2D Interativa

Recursos

  • Controle 2D: Eixos X e Y com valores de -100 a +100
  • Atualizações em Tempo Real: Atualizações instantâneas da posição via comunicação Bluetooth
  • Opção de Retorno Automático: Retorno automático configurável para a posição central (0, 0)
  • Sensibilidade Ajustável: Configure o limite mínimo de movimento para filtrar pequenas mudanças
  • Compatível com Robôs: Valores facilmente mapeados para as entradas do driver de motor
  • 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

Código do 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 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 apropriada e a porta COM.
  • Navegue até 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
  • Você será solicitado a instalar algumas outras dependências da biblioteca
  • Clique no botão Install All para instalar todas as dependências da biblioteca.
Dependência do DIYables Bluetooth para ESP32

Escolha um dos dois modos Bluetooth abaixo, de acordo com a sua necessidade:

Código do ESP32 para Bluetooth Clássico (funciona com o app somente no Android)

Observação: O Bluetooth Clássico NÃO é suportado no iOS. Se você precisa de suporte ao iOS, use o código BLE abaixo.

  • No Arduino IDE, vá em File Examples DIYables Bluetooth Esp32Bluetooth_Joystick, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - ESP32 Classic Bluetooth Joystick 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 Joystick feature: * - Interactive joystick control via Bluetooth * - Real-time X/Y coordinate values (-100 to +100) * - Control pins based on joystick position * * 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 the joystick * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothJoystick.h> #include <platforms/DIYables_Esp32Bluetooth.h> // Create Bluetooth instances DIYables_Esp32Bluetooth bluetooth("ESP32_Joystick"); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Joystick app instance // Configure with autoReturn=false and sensitivity=5 (minimum 5% change to trigger updates) DIYables_BluetoothJoystick bluetoothJoystick(false, 5); // Variables to store current joystick values int currentJoystickX = 0; int currentJoystickY = 0; void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 Joystick Example"); // TODO: initialize your hardware pins here // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add joystick app to server bluetoothServer.addApp(&bluetoothJoystick); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Set up joystick callback for position changes bluetoothJoystick.onJoystickValue([](int x, int y) { // Store the received values currentJoystickX = x; currentJoystickY = y; // Print joystick position values (-100 to +100) Serial.print("Joystick - X: "); Serial.print(x); Serial.print(", Y: "); Serial.println(y); // TODO: Add your control logic here based on joystick position // Examples: // - Control motors: if (x > 50) { /* move right */ } // - Control servos: servo.write(map(y, -100, 100, 0, 180)); // - Control LEDs: ledcWrite(channel, map(abs(x), 0, 100, 0, 255)); // - Send commands to other devices via Serial, I2C, SPI, etc. }); // Optional: Handle requests for current joystick values (when app loads) bluetoothJoystick.onGetConfig([]() { // Send the stored joystick values back to the app bluetoothJoystick.send(currentJoystickX, currentJoystickY); Serial.print("App requested values - Sent: X="); Serial.print(currentJoystickX); Serial.print(", Y="); Serial.println(currentJoystickY); }); // You can change configuration at runtime: // bluetoothJoystick.setAutoReturn(false); // Disable auto-return // bluetoothJoystick.setSensitivity(10.0); // Only send updates when joystick moves >10% (less sensitive) Serial.println("Waiting for Bluetooth connection..."); } void loop() { // Handle Bluetooth server communications bluetoothServer.loop(); // TODO: Add your main application code here delay(10); }
  • Clique no botão Upload no Arduino IDE para fazer o upload do código para o ESP32
  • Abra o Serial Monitor
  • Veja o resultado no Serial Monitor. Ele deve ser parecido com o 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 Joystick Example Waiting for Bluetooth connection...
Ln 11, Col 1
ESP32 Dev Module on COM15
2

Código do ESP32 para BLE (funciona com o app no Android e no iOS)

  • No Arduino IDE, vá em File Examples DIYables Bluetooth Esp32BLE_Joystick, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - ESP32 BLE Joystick Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Joystick feature: * - Interactive joystick control via Bluetooth * - Real-time X/Y coordinate values (-100 to +100) * - Control pins based on joystick position * * 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 the joystick * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothJoystick.h> #include <platforms/DIYables_Esp32BLE.h> // BLE Configuration const char* DEVICE_NAME = "ESP32BLE_Joystick"; 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 Joystick app instance DIYables_BluetoothJoystick bluetoothJoystick(false, 5); // Variables to store current joystick values int currentJoystickX = 0; int currentJoystickY = 0; void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 BLE Joystick Example"); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add joystick app to server bluetoothServer.addApp(&bluetoothJoystick); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Set up joystick callback for position changes bluetoothJoystick.onJoystickValue([](int x, int y) { currentJoystickX = x; currentJoystickY = y; Serial.print("Joystick - X: "); Serial.print(x); Serial.print(", Y: "); Serial.println(y); // TODO: Add your control logic here based on joystick position }); bluetoothJoystick.onGetConfig([]() { bluetoothJoystick.send(currentJoystickX, currentJoystickY); Serial.print("App requested values - Sent: X="); Serial.print(currentJoystickX); Serial.print(", Y="); Serial.println(currentJoystickY); }); Serial.println("Waiting for Bluetooth connection..."); } void loop() { bluetoothServer.loop(); delay(10); }
  • Clique no botão Upload no Arduino IDE para fazer o upload do código para o ESP32
  • Abra o Serial Monitor
  • Veja o resultado no Serial Monitor. Ele deve ser parecido com o 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 Joystick Example Waiting for Bluetooth connection...
Ln 11, Col 1
ESP32 Dev Module on COM15
2

App para Celular

  • Instale o DIYables Bluetooth App no seu smartphone: Android | iOS
  • Se você estiver usando o código do ESP32 para Bluetooth Clássico, você precisa parear o ESP32 com o seu celular Android antes de abrir o app:
    • Vá em Settings > Bluetooth no seu celular
    • Certifique-se de que o Bluetooth está ativado
    • Seu celular vai buscar os dispositivos disponíveis
    • Encontre e toque em "ESP32_Joystick" 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 do ESP32 para BLE, não é necessário parear. Basta ir para a próxima etapa.
  • Abra o DIYables Bluetooth App
  • 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 buscar e conectar a dispositivos Bluetooth
    • Permissão de Localização (somente Android 11 e anteriores) - exigida pelas versões mais antigas do Android para buscar dispositivos BLE
  • Certifique-se de que o Bluetooth está ativado no seu celular
  • Na tela inicial, toque no botão Connect. O app vai buscar dispositivos BLE e Bluetooth Clássico.
DIYables Bluetooth App - Tela Inicial com o Botão de Busca
  • Encontre e toque no seu dispositivo nos resultados da busca para conectar:
    • Para o Bluetooth Clássico: toque em "ESP32_Joystick"
    • Para o BLE: toque em "ESP32BLE_Joystick"
  • Depois de conectado, o app volta automaticamente para a tela inicial. Selecione o app Joystick no menu de apps.
DIYables Bluetooth App - Tela Inicial com o App Joystick

Observação: 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.

  • Mova o joystick em qualquer direção para enviar os valores das coordenadas X/Y
DIYables Bluetooth App - Tela do Joystick

Agora volte ao 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! Joystick - X: 50, Y: 0 Joystick - X: 75, Y: -30 Joystick - X: 0, Y: 100 Joystick - X: -60, Y: 45 Joystick - X: 0, Y: 0
Ln 11, Col 1
ESP32 Dev Module on COM15
2
  • Mova o joystick no app e observe os valores X/Y em tempo real no Serial Monitor

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

Configurar o Retorno Automático e a Sensibilidade

Defina o comportamento do joystick com os parâmetros do construtor:

// Create Joystick app instance // Parameters: autoReturn (bool), sensitivity (float - minimum % change to trigger update) DIYables_BluetoothJoystick bluetoothJoystick(false, 5); // Or change at runtime: bluetoothJoystick.setAutoReturn(true); // Enable auto-return to center bluetoothJoystick.setSensitivity(10.0); // Only send updates when joystick moves >10% // Read current configuration: bool autoReturn = bluetoothJoystick.getAutoReturn(); float sensitivity = bluetoothJoystick.getSensitivity();

Tratar Mudanças na Posição do Joystick

Use o callback onJoystickValue() para receber as coordenadas X/Y:

bluetoothJoystick.onJoystickValue([](int x, int y) { // x ranges from -100 (left) to +100 (right) // y ranges from -100 (down) to +100 (up) Serial.print("X: "); Serial.print(x); Serial.print(", Y: "); Serial.println(y); // TODO: Add your control logic here });

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

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

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

Enviar Valores ao App

Você pode enviar os valores de coordenadas do joystick do ESP32 para o app:

// Send X/Y coordinate values to the app bluetoothJoystick.send(currentJoystickX, currentJoystickY); // Send a text message bluetoothJoystick.send("Joystick calibrated");

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!"); bluetoothJoystick.send(currentJoystickX, currentJoystickY); }); // Called when the app disconnects from ESP32 bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); // Stop motors when connection is lost stopAllMotors(); }); // Check connection status anywhere in your code if (bluetoothServer.isConnected()) { // Do something only when connected }

Como Usar o Joystick

Controles da Interface do App

A interface de joystick do DIYables Bluetooth App oferece:

  • Pad Virtual do Joystick: Toque e arraste para controlar a posição
  • Exibição do Valor X: Mostra a posição horizontal atual (-100 a +100)
  • Exibição do Valor Y: Mostra a posição vertical atual (-100 a +100)

Faixas de Valores

O joystick fornece:

  • Eixo X: -100 (totalmente à esquerda) a 0 (centro) a +100 (totalmente à direita)
  • Eixo Y: -100 (totalmente para baixo) a 0 (centro) a +100 (totalmente para cima)
  • Posição Central: (0, 0) quando o joystick está em repouso

Exemplos de Programação

Tratador Básico de Joystick

void setup() { bluetoothJoystick.onJoystickValue([](int x, int y) { currentJoystickX = x; currentJoystickY = y; Serial.print("Joystick - X: "); Serial.print(x); Serial.print(", Y: "); Serial.println(y); }); }

Controle de Robô de Duas Rodas

const int MOTOR_LEFT_PWM = 16; const int MOTOR_LEFT_DIR1 = 18; const int MOTOR_LEFT_DIR2 = 19; const int MOTOR_RIGHT_PWM = 17; const int MOTOR_RIGHT_DIR1 = 21; const int MOTOR_RIGHT_DIR2 = 22; void setup() { // Configure motor pins pinMode(MOTOR_LEFT_PWM, OUTPUT); pinMode(MOTOR_LEFT_DIR1, OUTPUT); pinMode(MOTOR_LEFT_DIR2, OUTPUT); pinMode(MOTOR_RIGHT_PWM, OUTPUT); pinMode(MOTOR_RIGHT_DIR1, OUTPUT); pinMode(MOTOR_RIGHT_DIR2, OUTPUT); bluetoothJoystick.onJoystickValue([](int x, int y) { // Differential drive: mix X (turn) and Y (speed) int leftSpeed = constrain(y + x, -100, 100); int rightSpeed = constrain(y - x, -100, 100); // Set left motor direction and speed if (leftSpeed >= 0) { digitalWrite(MOTOR_LEFT_DIR1, HIGH); digitalWrite(MOTOR_LEFT_DIR2, LOW); } else { digitalWrite(MOTOR_LEFT_DIR1, LOW); digitalWrite(MOTOR_LEFT_DIR2, HIGH); } analogWrite(MOTOR_LEFT_PWM, map(abs(leftSpeed), 0, 100, 0, 255)); // Set right motor direction and speed if (rightSpeed >= 0) { digitalWrite(MOTOR_RIGHT_DIR1, HIGH); digitalWrite(MOTOR_RIGHT_DIR2, LOW); } else { digitalWrite(MOTOR_RIGHT_DIR1, LOW); digitalWrite(MOTOR_RIGHT_DIR2, HIGH); } analogWrite(MOTOR_RIGHT_PWM, map(abs(rightSpeed), 0, 100, 0, 255)); Serial.print("Left: "); Serial.print(leftSpeed); Serial.print("%, Right: "); Serial.print(rightSpeed); Serial.println("%"); }); }

Controle de Servo Pan-Tilt

#include <ESP32Servo.h> Servo panServo; // Horizontal (X axis) Servo tiltServo; // Vertical (Y axis) const int PAN_PIN = 13; const int TILT_PIN = 14; void setup() { panServo.attach(PAN_PIN); tiltServo.attach(TILT_PIN); panServo.write(90); // Center position tiltServo.write(90); bluetoothJoystick.onJoystickValue([](int x, int y) { // Map joystick values (-100 to +100) to servo angles (0 to 180) int panAngle = map(x, -100, 100, 0, 180); int tiltAngle = map(y, -100, 100, 0, 180); panServo.write(panAngle); tiltServo.write(tiltAngle); Serial.print("Pan: "); Serial.print(panAngle); Serial.print("°, Tilt: "); Serial.print(tiltAngle); Serial.println("°"); }); }

Indicador de Direção em Matriz de LED

// 4 directional LEDs const int LED_UP = 16; const int LED_DOWN = 17; const int LED_LEFT = 18; const int LED_RIGHT = 19; const int THRESHOLD = 30; // Minimum joystick value to activate LED void setup() { pinMode(LED_UP, OUTPUT); pinMode(LED_DOWN, OUTPUT); pinMode(LED_LEFT, OUTPUT); pinMode(LED_RIGHT, OUTPUT); bluetoothJoystick.onJoystickValue([](int x, int y) { // Light up LEDs based on joystick direction digitalWrite(LED_UP, y > THRESHOLD ? HIGH : LOW); digitalWrite(LED_DOWN, y < -THRESHOLD ? HIGH : LOW); digitalWrite(LED_RIGHT, x > THRESHOLD ? HIGH : LOW); digitalWrite(LED_LEFT, x < -THRESHOLD ? HIGH : LOW); // Show direction in Serial String direction = ""; if (y > THRESHOLD) direction += "UP "; if (y < -THRESHOLD) direction += "DOWN "; if (x > THRESHOLD) direction += "RIGHT "; if (x < -THRESHOLD) direction += "LEFT "; if (direction == "") direction = "CENTER"; Serial.println("Direction: " + direction); }); }

Técnicas Avançadas de Programação

Filtro de Zona Morta

const int DEAD_ZONE = 15; // Ignore joystick values within ±15 bluetoothJoystick.onJoystickValue([](int x, int y) { // Apply dead zone filter int filteredX = (abs(x) > DEAD_ZONE) ? x : 0; int filteredY = (abs(y) > DEAD_ZONE) ? y : 0; // Use filtered values for control controlMotors(filteredX, filteredY); });

Rampa de Velocidade

int targetX = 0, targetY = 0; int currentX = 0, currentY = 0; const int RAMP_RATE = 5; // Max change per update void setup() { bluetoothJoystick.onJoystickValue([](int x, int y) { targetX = x; targetY = y; }); } void loop() { bluetoothServer.loop(); // Gradually ramp to target values if (currentX < targetX) currentX = min(currentX + RAMP_RATE, targetX); else if (currentX > targetX) currentX = max(currentX - RAMP_RATE, targetX); if (currentY < targetY) currentY = min(currentY + RAMP_RATE, targetY); else if (currentY > targetY) currentY = max(currentY - RAMP_RATE, targetY); controlMotors(currentX, currentY); delay(20); }

Cálculo de Magnitude e Ângulo

bluetoothJoystick.onJoystickValue([](int x, int y) { // Calculate magnitude (distance from center, 0-100) float magnitude = sqrt(x * x + y * y); magnitude = constrain(magnitude, 0, 100); // Calculate angle in degrees (0° = right, 90° = up) float angle = atan2(y, x) * 180.0 / PI; Serial.print("Magnitude: "); Serial.print(magnitude, 1); Serial.print(", Angle: "); Serial.print(angle, 1); Serial.println("°"); // Use magnitude for speed and angle for direction int speed = map((int)magnitude, 0, 100, 0, 255); // Apply to your hardware... });

Exemplos de Integração com Hardware

Robô com Rodas Mecanum

// Mecanum wheel robot requires 4 motors const int MOTOR_FL = 16; // Front-Left const int MOTOR_FR = 17; // Front-Right const int MOTOR_BL = 18; // Back-Left const int MOTOR_BR = 19; // Back-Right void setupMecanumRobot() { bluetoothJoystick.onJoystickValue([](int x, int y) { // Mecanum wheel kinematics int fl = constrain(y + x, -100, 100); int fr = constrain(y - x, -100, 100); int bl = constrain(y - x, -100, 100); int br = constrain(y + x, -100, 100); setMotor(MOTOR_FL, fl); setMotor(MOTOR_FR, fr); setMotor(MOTOR_BL, bl); setMotor(MOTOR_BR, br); }); } void setMotor(int pin, int speed) { // Map -100..100 to PWM with direction analogWrite(pin, map(abs(speed), 0, 100, 0, 255)); }

Controle de Posição de Motor de Passo

#include <AccelStepper.h> AccelStepper stepperX(AccelStepper::DRIVER, 16, 17); AccelStepper stepperY(AccelStepper::DRIVER, 18, 19); void setup() { stepperX.setMaxSpeed(1000); stepperX.setAcceleration(500); stepperY.setMaxSpeed(1000); stepperY.setAcceleration(500); bluetoothJoystick.onJoystickValue([](int x, int y) { // Map joystick to stepper speed (-1000 to +1000 steps/sec) int speedX = map(x, -100, 100, -1000, 1000); int speedY = map(y, -100, 100, -1000, 1000); stepperX.setSpeed(speedX); stepperY.setSpeed(speedY); }); } void loop() { bluetoothServer.loop(); stepperX.runSpeed(); stepperY.runSpeed(); }

BLE vs Bluetooth Clássico - Qual Escolher?

RecursoBLE (Esp32BLE_Joystick)Bluetooth Clássico (Esp32Bluetooth_Joystick)
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)
Melhor ParaDispositivos a bateria, multiplataformaAlta taxa de transferência, somente Android

Solução de Problemas

Problemas Comuns

1. Não consigo encontrar o dispositivo no app

  • Certifique-se de que o ESP32 está ligado e que o sketch foi carregado
  • Para o BLE: Garanta que o Bluetooth e a Localização do seu celular estão ativados
  • Para o 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. O joystick não responde

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

3. Os valores do joystick parecem erráticos

  • Aumente o valor de sensibilidade para filtrar pequenos movimentos: bluetoothJoystick.setSensitivity(10.0)
  • Aplique um filtro de zona morta no seu callback
  • Verifique se há interferência de outros dispositivos Bluetooth

4. A conexão cai com frequência

  • Aproxime-se do ESP32 (reduza a distância)
  • Para o BLE: Verifique se há interferência de outros dispositivos BLE
  • Para o Bluetooth Clássico: Garanta uma alimentação estável para o ESP32
  • Verifique no Serial Monitor se há mensagens de desconexão/reconexão

5. Os motores não param quando o joystick é solto

  • Garanta que o retorno automático está habilitado: bluetoothJoystick.setAutoReturn(true)
  • Adicione uma verificação de zona morta no seu código de controle dos motores
  • Adicione uma parada de segurança no callback setOnDisconnected()

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
  • Esta configuração oferece ~3MB ao sacrificar a partição de OTA (atualização pelo ar)

Dicas de Depuração

Adicione uma depuração completa:

void debugJoystickValues(int x, int y) { float magnitude = sqrt(x * x + y * y); float angle = atan2(y, x) * 180.0 / PI; Serial.println("=== Joystick Debug ==="); Serial.println("X: " + String(x) + ", Y: " + String(y)); Serial.println("Magnitude: " + String(magnitude, 1)); Serial.println("Angle: " + String(angle, 1) + "°"); Serial.println("======================"); }

Ideias de Projetos

Projetos de Robótica

  • Robô de tração diferencial controlado por Bluetooth
  • Robô com rodas Mecanum ou omnidirecionais
  • Controle das juntas de um braço robótico
  • Controlador de estação terrestre para drone

Projetos de Câmera

  • Controle de suporte de câmera pan-tilt
  • Posicionamento de slider de câmera motorizado
  • Controle remoto de câmera de vigilância

Projetos de Jogos

  • Controle de jogo Bluetooth para jogos com ESP32
  • Jogo de navegação em labirinto
  • Jogos de joystick com matriz de LED (Snake, Pong)

Projetos Industriais

  • Controlador de jog para CNC
  • Posicionamento de plataforma ou mesa motorizada
  • Controle direcional de guindaste ou guincho

Integração com Outros Apps Bluetooth

Combine com o Bluetooth Slider

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

int maxSpeed = 100; bluetoothSlider.onSliderValue([](int slider1, int slider2) { maxSpeed = slider1; // Slider controls max speed }); bluetoothJoystick.onJoystickValue([](int x, int y) { // Scale joystick 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 Monitor

Use o joystick para o controle e o monitor para a telemetria:

bluetoothJoystick.onJoystickValue([](int x, int y) { controlMotors(x, y); // Send telemetry to monitor bluetoothMonitor.send("X=" + String(x) + " Y=" + String(y) + " Speed=" + String(sqrt(x*x + y*y), 0)); });

Próximos Passos

Depois de dominar o exemplo Bluetooth Joystick, experimente:

  1. Bluetooth Slider - Para o controle preciso de valores analógicos
  2. Bluetooth Digital Pins - Para o controle discreto de ligar/desligar
  3. Bluetooth Monitor - Para depurar os valores do joystick
  4. Multiple Bluetooth Apps - Combinando o joystick com sliders e outros controles

Suporte

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