Arduino UNO R4 WiFi Bluetooth Exemple Digital Pins - Tutoriel Contrôle des Broches GPIO via BLE

Vue d'ensemble

L'exemple Bluetooth Digital Pins offre un contrôle et une surveillance des broches GPIO à distance, accessibles via l'application DIYables Bluetooth STEM. Conçu pour Arduino UNO R4 WiFi utilisant BLE (Bluetooth Low Energy) pour contrôler les broches de sortie et surveiller les broches d'entrée sans fil depuis votre smartphone. Parfait pour le contrôle de relais, la surveillance de boutons, la commutation de LED et toute application nécessitant un accès distant aux broches.

Note : L'Arduino UNO R4 WiFi ne supporte que BLE (Bluetooth Low Energy). Il ne supporte pas le Bluetooth Classic. L'application DIYables Bluetooth supporte à la fois BLE et Bluetooth Classic sur Android, et BLE sur iOS. Puisque cette carte utilise BLE, l'application fonctionne sur Android et iOS.

Arduino UNO R4 WiFi Bluetooth Exemple Digital Pins - Tutoriel Contrôle des Broches GPIO via BLE

Fonctionnalités

  • Contrôle de Sortie : Définir les broches digitales HIGH/LOW à distance
  • Surveillance d'Entrée : Lire les états des broches digitales et analogiques
  • Broches Nommées : Assigner des noms conviviaux à chaque broche (ex. "LED", "Relais")
  • Mises à jour Temps Réel : Pousser les changements d'état des broches vers l'application
  • Jusqu'à 16 Broches : Contrôler plusieurs broches simultanément
  • Fonctionne sur Android et iOS : BLE est supporté sur les deux plateformes
  • Pas d'Appairage Requis : BLE se connecte automatiquement sans appairage manuel

Code Arduino UNO R4 WiFi

Étapes Rapides

Suivez ces instructions étape par étape :

  • Si c'est votre première fois avec l'Arduino UNO R4 WiFi, consultez le Arduino UNO R4 - Installation du logiciel..
  • Connectez la carte Arduino UNO R4 WiFi à votre ordinateur avec un câble USB.
  • Lancez l'IDE Arduino sur votre ordinateur.
  • Sélectionnez la carte Arduino UNO R4 WiFi et le port COM approprié.
  • Naviguez vers l'icône Libraries dans la barre de gauche de l'IDE Arduino.
  • Recherchez "DIYables Bluetooth", puis trouvez la bibliothèque DIYables Bluetooth par DIYables
  • Cliquez sur le bouton Install pour installer la bibliothèque.
Bibliothèque Arduino UNO R4 DIYables Bluetooth
  • Il vous sera demandé d'installer d'autres dépendances de bibliothèque
  • Cliquez sur le bouton Install All pour installer toutes les dépendances de bibliothèque.
Dépendances Arduino UNO R4 DIYables Bluetooth

Code BLE

  • Dans l'IDE Arduino, allez à File Examples DIYables Bluetooth ArduinoBLE_PinControl exemple, ou copiez le code ci-dessus et collez-le dans l'éditeur de l'IDE Arduino
/* * DIYables Bluetooth Library - Bluetooth Pin Control/Monitor Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Pin Control/Monitor feature: * - Control digital output pins via Bluetooth * - Monitor digital input pins * - Monitor analog input pins * - Configure pin modes (INPUT/OUTPUT) * * 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 pins * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothPinControl.h> #include <platforms/DIYables_ArduinoBLE.h> // BLE Configuration const char* DEVICE_NAME = "Arduino_Pins"; 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 Pin Control/Monitor app instance DIYables_BluetoothPinControl bluetoothPins; // Pin configuration const int LED_PIN = 13; const int OUTPUT_PIN_1 = 12; const int OUTPUT_PIN_2 = 11; const int INPUT_PIN_1 = 7; const int INPUT_PIN_2 = 6; const int ANALOG_PIN_1 = A0; const int ANALOG_PIN_2 = A1; void setup() { Serial.begin(9600); while (!Serial); Serial.println("DIYables Bluetooth - Pin Control/Monitor Example"); // Initialize pins pinMode(LED_PIN, OUTPUT); pinMode(OUTPUT_PIN_1, OUTPUT); pinMode(OUTPUT_PIN_2, OUTPUT); pinMode(INPUT_PIN_1, INPUT_PULLUP); pinMode(INPUT_PIN_2, INPUT_PULLUP); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add digital pins app to server bluetoothServer.addApp(&bluetoothPins); // Configure which pins are accessible via Bluetooth with custom names bluetoothPins.enablePin(LED_PIN, BT_PIN_OUTPUT, "LED"); bluetoothPins.enablePin(OUTPUT_PIN_1, BT_PIN_OUTPUT, "Out1"); bluetoothPins.enablePin(OUTPUT_PIN_2, BT_PIN_OUTPUT, "Out2"); bluetoothPins.enablePin(INPUT_PIN_1, BT_PIN_INPUT, "Btn1"); bluetoothPins.enablePin(INPUT_PIN_2, BT_PIN_INPUT, "Btn2"); bluetoothPins.enablePin(ANALOG_PIN_1, BT_PIN_INPUT, "A0"); bluetoothPins.enablePin(ANALOG_PIN_2, BT_PIN_INPUT, "A1"); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Set up callback for pin write commands bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); Serial.print("Pin "); Serial.print(pin); Serial.print(" set to "); Serial.println(state ? "HIGH" : "LOW"); }); // Set up callback for pin read commands bluetoothPins.onPinRead([](int pin) -> int { // Read analog pins with analogRead, digital pins with digitalRead int state; if (pin == ANALOG_PIN_1 || pin == ANALOG_PIN_2) { state = analogRead(pin); Serial.print("Analog pin "); Serial.print(pin); Serial.print(" read: "); Serial.println(state); } else { state = digitalRead(pin); Serial.print("Digital pin "); Serial.print(pin); Serial.print(" read: "); Serial.println(state ? "HIGH" : "LOW"); } return state; }); // Set up callback for pin mode changes bluetoothPins.onPinModeChange([](int pin, int mode) { pinMode(pin, mode == BT_PIN_OUTPUT ? OUTPUT : INPUT_PULLUP); Serial.print("Pin "); Serial.print(pin); Serial.print(" mode changed to "); Serial.println(mode == BT_PIN_OUTPUT ? "OUTPUT" : "INPUT"); }); Serial.println("Waiting for Bluetooth connection..."); Serial.print("Enabled pins: "); Serial.println(bluetoothPins.getEnabledPinCount()); } void loop() { // Handle Bluetooth server communications bluetoothServer.loop(); // Optional: Monitor input pins and send updates static unsigned long lastInputCheck = 0; static int lastInputState1 = HIGH; static int lastInputState2 = HIGH; static int lastAnalogState1 = 0; static int lastAnalogState2 = 0; if (millis() - lastInputCheck >= 100) { lastInputCheck = millis(); // Check digital input pin 1 int currentState1 = digitalRead(INPUT_PIN_1); if (currentState1 != lastInputState1) { lastInputState1 = currentState1; bluetoothPins.updatePinState(INPUT_PIN_1, currentState1); Serial.print("Input pin "); Serial.print(INPUT_PIN_1); Serial.print(" changed to "); Serial.println(currentState1 ? "HIGH" : "LOW"); } // Check digital input pin 2 int currentState2 = digitalRead(INPUT_PIN_2); if (currentState2 != lastInputState2) { lastInputState2 = currentState2; bluetoothPins.updatePinState(INPUT_PIN_2, currentState2); Serial.print("Input pin "); Serial.print(INPUT_PIN_2); Serial.print(" changed to "); Serial.println(currentState2 ? "HIGH" : "LOW"); } // Check analog input 1 (send update if changed by more than 10) int currentAnalog1 = analogRead(ANALOG_PIN_1); if (abs(currentAnalog1 - lastAnalogState1) > 10) { lastAnalogState1 = currentAnalog1; bluetoothPins.updatePinState(ANALOG_PIN_1, currentAnalog1); Serial.print("Analog pin "); Serial.print(ANALOG_PIN_1); Serial.print(" changed to "); Serial.println(currentAnalog1); } // Check analog input 2 (send update if changed by more than 10) int currentAnalog2 = analogRead(ANALOG_PIN_2); if (abs(currentAnalog2 - lastAnalogState2) > 10) { lastAnalogState2 = currentAnalog2; bluetoothPins.updatePinState(ANALOG_PIN_2, currentAnalog2); Serial.print("Analog pin "); Serial.print(ANALOG_PIN_2); Serial.print(" changed to "); Serial.println(currentAnalog2); } } delay(10); }
  • Cliquez sur le bouton Upload dans l'IDE Arduino pour téléverser le code vers Arduino UNO R4 WiFi
  • Ouvrez le Serial Monitor
  • Vérifiez le résultat sur Serial Monitor. Il ressemble à ceci :
COM6
Send
DIYables Bluetooth - Pin Control/Monitor Example Waiting for Bluetooth connection... Enabled pins: 7
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Application Mobile

  • Installez l'application DIYables Bluetooth sur votre smartphone : Android | iOS

Note : L'application DIYables Bluetooth supporte à la fois BLE et Bluetooth Classic sur Android, et BLE sur iOS. Puisque l'Arduino UNO R4 WiFi utilise BLE, l'application fonctionne sur Android et iOS. Aucun appairage manuel n'est nécessaire pour BLE — il suffit de scanner et se connecter.

  • Ouvrez l'application DIYables Bluetooth
  • Lors de la première ouverture de l'application, elle demandera des permissions. Veuillez accorder les suivantes :
    • Permission Nearby Devices (Android 12+) / permission Bluetooth (iOS) - requise pour scanner et se connecter aux appareils Bluetooth
    • Permission Location (Android 11 et antérieur uniquement) - requise par les anciennes versions Android pour scanner les appareils BLE
  • Assurez-vous que le Bluetooth est activé sur votre téléphone
  • Sur l'écran d'accueil, appuyez sur le bouton Connect. L'application va scanner les appareils BLE.
Application DIYables Bluetooth - Écran d'accueil avec bouton Scan
  • Trouvez et appuyez sur "Arduino_Pins" dans les résultats de scan pour vous connecter.
  • Une fois connecté, l'application revient automatiquement à l'écran d'accueil. Sélectionnez l'application Digital Pins depuis le menu des applications.
Application DIYables Bluetooth - Écran d'accueil avec application Digital Pins

Note : Vous pouvez appuyer sur l'icône de paramètres sur l'écran d'accueil pour masquer/afficher les applications sur l'écran d'accueil. Pour plus de détails, consultez le Manuel Utilisateur de l'Application DIYables Bluetooth.

  • Vous verrez la liste des broches activées avec leurs noms et états actuels
  • Appuyez sur les broches de sortie pour basculer HIGH/LOW, et regardez les valeurs des broches d'entrée se mettre à jour
Application DIYables Bluetooth - Écran Digital Pins

Maintenant regardez à nouveau le Serial Monitor dans l'IDE Arduino. Vous verrez :

COM6
Send
Bluetooth connected! Pin 13 set to HIGH Pin 13 set to LOW Digital pin 7 read: HIGH
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Personnalisation Créative - Adaptez le Code à Votre Projet

Activer les Broches

// Enable pins with mode and friendly name bluetoothPins.enablePin(13, BT_PIN_OUTPUT, "LED"); bluetoothPins.enablePin(12, BT_PIN_OUTPUT, "Relay"); bluetoothPins.enablePin(7, BT_PIN_INPUT, "Button"); bluetoothPins.enablePin(A0, BT_PIN_INPUT, "Sensor"); // Check enabled pin count int count = bluetoothPins.getEnabledPinCount();

Gérer l'Écriture/Lecture/Mode des Broches

bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); Serial.print("Pin "); Serial.print(pin); Serial.println(state ? " ? HIGH" : " ? LOW"); }); bluetoothPins.onPinRead([](int pin) -> int { if (pin >= A0) { return analogRead(pin); } return digitalRead(pin); }); bluetoothPins.onPinModeChange([](int pin, int mode) { pinMode(pin, mode == BT_PIN_OUTPUT ? OUTPUT : INPUT_PULLUP); });

Pousser les Changements d'État

// Notify the app when a pin state changes bluetoothPins.updatePinState(7, digitalRead(7)); bluetoothPins.updatePinState(A0, analogRead(A0));

Exemples de Programmation

Contrôle de Relais avec Surveillance de Bouton

const int RELAY_PIN = 12; const int BUTTON_PIN = 7; void setup() { pinMode(RELAY_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT_PULLUP); bluetoothPins.enablePin(RELAY_PIN, BT_PIN_OUTPUT, "Relay"); bluetoothPins.enablePin(BUTTON_PIN, BT_PIN_INPUT, "Button"); bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); }); } void loop() { bluetoothServer.loop(); // Monitor button and push changes static int lastState = HIGH; int state = digitalRead(BUTTON_PIN); if (state != lastState) { lastState = state; bluetoothPins.updatePinState(BUTTON_PIN, state); } delay(10); }

Contrôleur Multi-LED

const int LED_PINS[] = {8, 9, 10, 11, 12, 13}; const char* LED_NAMES[] = {"Red", "Green", "Blue", "Yellow", "White", "Built-in"}; const int NUM_LEDS = 6; void setup() { for (int i = 0; i < NUM_LEDS; i++) { pinMode(LED_PINS[i], OUTPUT); bluetoothPins.enablePin(LED_PINS[i], BT_PIN_OUTPUT, LED_NAMES[i]); } bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); }); }

Dépannage

Problèmes Courants

1. Impossible de trouver l'appareil dans l'application

  • Assurez-vous que l'Arduino UNO R4 WiFi est sous tension et que le sketch est téléversé
  • Vérifiez que le Bluetooth de votre téléphone est activé
  • Sur Android 11 et antérieur, activez aussi les services de localisation

2. Le basculement des broches ne fonctionne pas

  • Vérifiez que la broche est activée avec le mode BT_PIN_OUTPUT
  • Vérifiez que le callback onPinWrite est configuré
  • Vérifiez les connexions de câblage

3. Les broches d'entrée ne se mettent pas à jour

  • Assurez-vous que updatePinState() est appelé quand l'état de la broche change
  • Vérifiez la fréquence de polling dans la boucle

4. Les valeurs analogiques ne s'affichent pas

  • Utilisez analogRead() dans le callback onPinRead pour les broches analogiques
  • Les broches analogiques retournent des valeurs 0-1023

5. La connexion se coupe fréquemment

  • Rapprochez-vous de l'Arduino (réduire la distance)
  • Assurez-vous d'une alimentation USB stable

6. Le téléversement échoue ou la carte n'est pas reconnue

  • Installez le dernier package de carte Arduino UNO R4 via Board Manager
  • Essayez un câble USB ou port différent

Idées de Projets

  • Panneau de contrôle multi-relais
  • Moniteur de boutons et interrupteurs
  • Contrôleur d'éclairage LED
  • Panneau d'interrupteurs domotiques
  • Tableau de bord d'entrées capteurs

Étapes Suivantes

Après avoir maîtrisé l'exemple Bluetooth Digital Pins, essayez :

  1. Bluetooth Slider - Pour le contrôle de valeurs analogiques
  2. Bluetooth Monitor - Pour les retours de statut textuels
  3. Bluetooth Table - Pour l'affichage structuré du statut des broches
  4. Multiples Applications Bluetooth - Combiner le contrôle des broches avec d'autres applications

Support

Pour une aide supplémentaire :

  • Consultez la documentation de référence API
  • Forums de la communauté Arduino

※ NOS MESSAGES

  • N'hésitez pas à partager le lien de ce tutoriel. Cependant, veuillez ne pas utiliser notre contenu sur d'autres sites web. Nous avons investi beaucoup d'efforts et de temps pour créer ce contenu, veuillez respecter notre travail !