Exemplo de Joystick Bluetooth com Arduino UNO R4 WiFi - Tutorial de Controle Direcional 2D via BLE

Visão Geral

O exemplo de Joystick Bluetooth oferece um controle de joystick 2D interativo, acessível pelo app DIYables Bluetooth STEM. Feito para o Arduino UNO R4 WiFi usando BLE (Bluetooth Low Energy) para receber coordenadas X/Y em tempo real (-100 a +100) para controle direcional. Perfeito para navegação de robôs, servos pan-tilt, controle de motores e controles de jogos.

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 Joystick Bluetooth com Arduino UNO R4 WiFi - Tutorial de Controle Direcional 2D via BLE

Recursos

  • Controle 2D: eixos X e Y com faixa de -100 a +100
  • Sensibilidade Configurável: limite mínimo de movimento para disparar as atualizações
  • Opção de Retorno Automático: o joystick pode voltar ao centro quando for solto
  • Valores em Tempo Real: atualizações contínuas da posição enquanto você arrasta
  • 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_Joystick para abrir o exemplo, ou copie o código acima e cole no editor do Arduino IDE
/* * DIYables Bluetooth Library - Bluetooth 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: * - 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 the joystick * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothJoystick.h> #include <platforms/DIYables_ArduinoBLE.h> // BLE Configuration const char* DEVICE_NAME = "Arduino_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_ArduinoBLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID); 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(9600); while (!Serial); Serial.println("DIYables Bluetooth - 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: analogWrite(LED_PIN, 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 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 - Joystick 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_Joystick" nos resultados da busca para conectar.
  • Depois de conectado, o app volta automaticamente para a tela inicial. Selecione o app Joystick no menu de apps.
DIYables Bluetooth App - Home Screen with Joystick 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 o joystick em qualquer direção
DIYables Bluetooth App - Joystick 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! Joystick - X: 50, Y: 0 Joystick - X: 100, Y: 50 Joystick - X: 0, Y: -75 Joystick - X: 0, Y: 0
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2

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

Tratar os Valores do Joystick

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 });

Configurar as Opções do Joystick

// Constructor: DIYables_BluetoothJoystick(autoReturn, sensitivity) DIYables_BluetoothJoystick bluetoothJoystick(false, 5); // Change settings at runtime bluetoothJoystick.setAutoReturn(true); // Auto-center when released bluetoothJoystick.setSensitivity(10.0); // Only update when moved >10%

Tratar a Solicitação de Configuração

bluetoothJoystick.onGetConfig([]() { bluetoothJoystick.send(currentJoystickX, currentJoystickY); });

Exemplos de Programação

Robô de Tração Diferencial

const int LEFT_MOTOR_PIN = 9; const int RIGHT_MOTOR_PIN = 10; const int LEFT_DIR_PIN = 7; const int RIGHT_DIR_PIN = 8; bluetoothJoystick.onJoystickValue([](int x, int y) { // Differential drive: mix X and Y int leftSpeed = constrain(y + x, -100, 100); int rightSpeed = constrain(y - x, -100, 100); // Set direction digitalWrite(LEFT_DIR_PIN, leftSpeed >= 0 ? HIGH : LOW); digitalWrite(RIGHT_DIR_PIN, rightSpeed >= 0 ? HIGH : LOW); // Set speed (PWM) analogWrite(LEFT_MOTOR_PIN, map(abs(leftSpeed), 0, 100, 0, 255)); analogWrite(RIGHT_MOTOR_PIN, map(abs(rightSpeed), 0, 100, 0, 255)); });

Servo Pan-Tilt

#include <Servo.h> Servo panServo, tiltServo; void setup() { panServo.attach(9); tiltServo.attach(10); bluetoothJoystick.onJoystickValue([](int x, int y) { int panAngle = map(x, -100, 100, 0, 180); int tiltAngle = map(y, -100, 100, 0, 180); panServo.write(panAngle); tiltServo.write(tiltAngle); }); }

Direção com Zona Morta

const int DEAD_ZONE = 15; bluetoothJoystick.onJoystickValue([](int x, int y) { if (abs(x) < DEAD_ZONE && abs(y) < DEAD_ZONE) { Serial.println("STOPPED"); return; } if (abs(y) > abs(x)) { Serial.println(y > 0 ? "FORWARD" : "BACKWARD"); } else { Serial.println(x > 0 ? "RIGHT" : "LEFT"); } });

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 joystick não responde

  • Verifique o status da conexão Bluetooth no app
  • Confirme que o callback onJoystickValue está configurado corretamente
  • Verifique as mensagens de conexão no Serial Monitor

3. O movimento parece lento

  • Reduza o valor de sensibilidade para ter atualizações mais frequentes
  • Garanta que bluetoothServer.loop() seja chamado sem atrasos longos

4. Os valores saltam ou são inconsistentes

  • Adicione um filtro de zona morta para movimentos pequenos
  • Verifique a configuração de sensibilidade

5. A conexão cai com frequência

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

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

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

Ideias de Projetos

  • Controle remoto sem fio para robô
  • Suporte pan-tilt para câmera
  • Controle de 2 eixos para braço robótico
  • Controlador de posição para matriz de LEDs
  • Controle de jogos para jogos com Arduino

Próximos Passos

Depois de dominar o exemplo de Joystick Bluetooth, experimente:

  1. Bluetooth Slider - Para controle de valores lineares
  2. Bluetooth Rotator - Para controle angular
  3. Bluetooth Monitor - Para retorno de status
  4. Multiple Bluetooth Apps - Combinando o joystick com outros controles

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!