ESP32 Bluetooth Broches Numériques - Tutoriel Interface de Contrôle et Surveillance des Broches

Aperçu

L'exemple Bluetooth Broches Numériques fournit un contrôle à distance et une surveillance des broches GPIO de l'ESP32 via l'application DIYables Bluetooth STEM. Conçu pour les cartes ESP32 avec support pour les connexions BLE (Bluetooth Low Energy) et Bluetooth Classique. Configurez les broches comme entrées ou sorties, basculez les broches de sortie, lisez les états d'entrées numériques et analogiques, et recevez des notifications en temps réel des changements de broches — parfait pour la domotique, le contrôle de relais, la surveillance de boutons, et la lecture de capteurs.

Cet exemple supporte deux modes Bluetooth :

  • ESP32 BLE (Bluetooth Low Energy) : Fonctionne sur Android et iOS
  • ESP32 Bluetooth Classique : Fonctionne sur Android uniquement. iOS ne supporte pas le Bluetooth Classique. Utilisez BLE si vous avez besoin du support iOS.
ESP32 Bluetooth Broches Numériques - Tutoriel Interface de Contrôle et Surveillance des Broches

Fonctionnalités

  • Contrôle de Broches de Sortie : Basculez les broches de sortie numériques HIGH/LOW depuis l'application
  • Surveillance de Broches d'Entrée : Lisez les états des broches d'entrée numériques et analogiques
  • Noms de Broches Personnalisés : Attribuez des noms conviviaux à chaque broche (ex. "LED", "Btn1", "A34")
  • Mises à Jour en Temps Réel : Notifications automatiques lorsque les états des broches d'entrée changent
  • Jusqu'à 16 Broches : Support pour jusqu'à 16 broches configurables simultanément
  • Modes Mixtes : Combinez broches d'entrée et de sortie dans la même configuration
  • BLE & Bluetooth Classique : Choisissez le mode Bluetooth qui convient à votre projet
  • Multi-plateforme : Le mode BLE fonctionne sur Android et iOS ; le Bluetooth Classique fonctionne sur Android

Matériel Requis

1×Module de développement ESP32 ESP-WROOM-32
1×Alternativement: ESP32 Uno-form board
1×Alternativement: ESP32 S3 Uno-form board
1×Câble USB Type-C
1×Plaque d'essai
1×Fils de Connexion
1×Recommandé: Carte d'extension à bornier à vis pour ESP32
1×Recommandé: Breakout Expansion Board for ESP32
1×Recommandé: Répartiteur d'alimentation pour ESP32

Ou vous pouvez acheter les kits suivants:

1×Kit de Démarrage DIYables ESP32 (ESP32 inclus)
1×Kit de Capteurs DIYables (30 capteurs/écrans)
1×Kit de Capteurs DIYables (18 capteurs/écrans)
Divulgation : Certains des liens fournis dans cette section sont des liens affiliés Amazon. Nous pouvons recevoir une commission pour tout achat effectué via ces liens, sans coût supplémentaire pour vous. Nous vous remercions de votre soutien.

Code ESP32

Étapes Rapides

Suivez ces instructions étape par étape :

  • Si c'est la première fois que vous utilisez l'ESP32, référez-vous au tutoriel sur Installation du logiciel ESP32..
  • Connectez la carte ESP32 à votre ordinateur en utilisant un câble USB.
  • Lancez l'Arduino IDE sur votre ordinateur.
  • Sélectionnez la carte ESP32 appropriée et le port COM.
  • Naviguez vers l'icône Libraries dans la barre de gauche de l'Arduino IDE.
  • Recherchez "DIYables Bluetooth", puis trouvez la librairie DIYables Bluetooth par DIYables
  • Cliquez sur le bouton Install pour installer la librairie.
ESP32 DIYables Bluetooth library
  • Il vous sera demandé d'installer d'autres dépendances de librairie
  • Cliquez sur le bouton Install All pour installer toutes les dépendances de librairie.
ESP32 DIYables Bluetooth dependency

Choisissez l'un des deux modes Bluetooth ci-dessous selon vos besoins :

Code ESP32 Bluetooth Classique (fonctionne avec l'application sur Android uniquement)

Note : Le Bluetooth Classique n'est PAS supporté sur iOS. Si vous avez besoin du support iOS, utilisez le code BLE ci-dessous.

  • Dans l'Arduino IDE, allez à File Examples DIYables Bluetooth Esp32Bluetooth_PinControl exemple, ou copiez le code ci-dessus et collez-le dans l'éditeur de l'Arduino IDE
/* * DIYables Bluetooth Library - ESP32 Classic Bluetooth Pin Control 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 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: * - 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 pins * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothPinControl.h> #include <platforms/DIYables_Esp32Bluetooth.h> // Create Bluetooth instances DIYables_Esp32Bluetooth bluetooth("ESP32_Pins"); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Pin Control/Monitor app instance DIYables_BluetoothPinControl bluetoothPins; // Pin configuration (adjust for your ESP32 board) const int LED_PIN = 2; // Built-in LED on most ESP32 boards const int OUTPUT_PIN_1 = 16; const int OUTPUT_PIN_2 = 17; const int INPUT_PIN_1 = 18; const int INPUT_PIN_2 = 19; const int ANALOG_PIN_1 = 34; // ESP32 ADC1 pins (input only) const int ANALOG_PIN_2 = 35; void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 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, "A34"); bluetoothPins.enablePin(ANALOG_PIN_2, BT_PIN_INPUT, "A35"); // 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 50 - ESP32 has 12-bit ADC) int currentAnalog1 = analogRead(ANALOG_PIN_1); if (abs(currentAnalog1 - lastAnalogState1) > 50) { 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 50) int currentAnalog2 = analogRead(ANALOG_PIN_2); if (abs(currentAnalog2 - lastAnalogState2) > 50) { 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'Arduino IDE pour téléverser le code sur l'ESP32
  • Ouvrez le Moniteur Série
  • Vérifiez le résultat dans le Moniteur Série. Il ressemble à ceci :
COM6
Send
DIYables Bluetooth - ESP32 Pin Control/Monitor Example Waiting for Bluetooth connection... Enabled pins: 7
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Code ESP32 BLE (fonctionne avec l'application sur Android et iOS)

  • Dans l'Arduino IDE, allez à File Examples DIYables Bluetooth Esp32BLE_PinControl exemple, ou copiez le code ci-dessus et collez-le dans l'éditeur de l'Arduino IDE
/* * DIYables Bluetooth Library - ESP32 BLE 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: * - 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 pins * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothPinControl.h> #include <platforms/DIYables_Esp32BLE.h> // BLE Configuration const char* DEVICE_NAME = "ESP32BLE_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_Esp32BLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Pin Control/Monitor app instance DIYables_BluetoothPinControl bluetoothPins; // Pin configuration (ESP32 GPIOs) const int LED_PIN = 2; // Built-in LED const int OUTPUT_PIN_1 = 16; const int OUTPUT_PIN_2 = 17; const int INPUT_PIN_1 = 25; const int INPUT_PIN_2 = 26; const int ANALOG_PIN_1 = 34; // Input-only ADC pin const int ANALOG_PIN_2 = 35; // Input-only ADC pin void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 BLE 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, "A34"); bluetoothPins.enablePin(ANALOG_PIN_2, BT_PIN_INPUT, "A35"); // 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 { 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() { bluetoothServer.loop(); 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(); 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"); } 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"); } // ESP32 has 12-bit ADC (0-4095) int currentAnalog1 = analogRead(ANALOG_PIN_1); if (abs(currentAnalog1 - lastAnalogState1) > 40) { // ~1% of 4095 lastAnalogState1 = currentAnalog1; bluetoothPins.updatePinState(ANALOG_PIN_1, currentAnalog1); Serial.print("Analog pin "); Serial.print(ANALOG_PIN_1); Serial.print(" changed to "); Serial.println(currentAnalog1); } int currentAnalog2 = analogRead(ANALOG_PIN_2); if (abs(currentAnalog2 - lastAnalogState2) > 40) { 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'Arduino IDE pour téléverser le code sur l'ESP32
  • Ouvrez le Moniteur Série
  • Vérifiez le résultat dans le Moniteur Série. Il ressemble à ceci :
COM6
Send
DIYables Bluetooth - ESP32 BLE 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
  • Si vous utilisez le code ESP32 Bluetooth Classique, vous devez appairer l'ESP32 avec votre téléphone Android avant d'ouvrir l'application :
    • Allez dans les Paramètres > Bluetooth de votre téléphone
    • Assurez-vous que le Bluetooth est activé
    • Votre téléphone va scanner les appareils disponibles
    • Trouvez et appuyez sur "ESP32_Pins" dans la liste des appareils disponibles
    • Confirmez la demande d'appairage (aucun code PIN requis)
    • Attendez qu'il affiche "Paired" sous le nom de l'appareil
  • Si vous utilisez le code ESP32 BLE, aucun appairage n'est nécessaire. Passez simplement à l'étape suivante.
  • Ouvrez l'Application DIYables Bluetooth
  • Lors de la première ouverture de l'application, elle demandera des permissions. Veuillez accorder les suivantes :
    • Permission Appareils à proximité (Android 12+) / Permission Bluetooth (iOS) - requise pour scanner et se connecter aux appareils Bluetooth
    • Permission Localisation (Android 11 et versions antérieures 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 à la fois les appareils BLE et Bluetooth Classique.
DIYables Bluetooth App - Écran d'Accueil avec Bouton de Scan
  • Trouvez et appuyez sur votre appareil dans les résultats de scan pour vous connecter :
    • Pour Bluetooth Classique : appuyez sur "ESP32_Pins"
    • Pour BLE : appuyez sur "ESP32BLE_Pins"
  • Une fois connecté, l'application retourne automatiquement à l'écran d'accueil. Sélectionnez l'application Digital Pins dans le menu des applications.
DIYables Bluetooth App - Écran d'Accueil avec App Digital Pins

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

  • Basculez les broches de sortie en appuyant dessus, et regardez les broches d'entrée se mettre à jour en temps réel
DIYables Bluetooth App - Écran Digital Pins

Maintenant regardez de nouveau le Moniteur Série dans l'Arduino IDE. Vous verrez :

COM6
Send
Bluetooth connected! Pin 2 set to HIGH Pin 16 set to LOW Input pin 18 changed to LOW Analog pin 34 changed to 2048
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • Basculez les broches dans l'application et regardez le retour en temps réel dans le Moniteur Série

Personnalisation Créative - Adaptez le Code à Votre Projet

Configurer les Broches

Activez les broches avec des noms personnalisés et des modes :

// Activer des broches individuelles avec mode et nom personnalisé bluetoothPins.enablePin(2, BT_PIN_OUTPUT, "LED"); // LED intégrée bluetoothPins.enablePin(16, BT_PIN_OUTPUT, "Relay1"); // Contrôle relais bluetoothPins.enablePin(17, BT_PIN_OUTPUT, "Relay2"); // Contrôle relais bluetoothPins.enablePin(18, BT_PIN_INPUT, "Button"); // Entrée bouton bluetoothPins.enablePin(34, BT_PIN_INPUT, "Sensor"); // Capteur analogique // Désactiver une broche spécifique bluetoothPins.disablePin(17); // Vérifier le statut d'une broche bool isEnabled = bluetoothPins.isPinEnabled(2); int mode = bluetoothPins.getPinMode(2); int count = bluetoothPins.getEnabledPinCount();

Gérer les Commandes d'Écriture de Broche

Utilisez le callback onPinWrite() pour contrôler le matériel lorsque l'application bascule une broche :

bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); Serial.print("Pin "); Serial.print(pin); Serial.print(" set to "); Serial.println(state ? "HIGH" : "LOW"); });

Gérer les Commandes de Lecture de Broche

Utilisez le callback onPinRead() pour retourner les états des broches à l'application :

bluetoothPins.onPinRead([](int pin) -> int { if (pin == 34 || pin == 35) { // Lire la valeur analogique pour les broches ADC return analogRead(pin); } else { // Lire la valeur numérique pour les autres broches return digitalRead(pin); } });

Gérer les Changements de Mode de Broche

Utilisez le callback onPinModeChange() pour changer dynamiquement les modes de broche :

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

Envoyer des Mises à Jour d'État de Broche en Temps Réel

Poussez les changements d'état de broche vers l'application depuis votre code :

// Détecter les changements d'entrée et envoyer les mises à jour int currentState = digitalRead(18); if (currentState != lastState) { lastState = currentState; bluetoothPins.updatePinState(18, currentState); } // Envoyer les mises à jour de valeur analogique int analogValue = analogRead(34); if (abs(analogValue - lastAnalogValue) > 50) { lastAnalogValue = analogValue; bluetoothPins.updatePinState(34, analogValue); }

Gérer les Événements de Connexion

bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); // Sécurité : éteindre toutes les sorties lors de la déconnexion digitalWrite(2, LOW); digitalWrite(16, LOW); digitalWrite(17, LOW); });

Comment Utiliser les Broches Numériques

Contrôles de l'Interface de l'Application

L'interface des broches numériques dans l'Application DIYables Bluetooth fournit :

  • Liste des Broches : Affiche toutes les broches activées avec noms et états actuels
  • Boutons de Basculement : Appuyez sur les broches de sortie pour basculer HIGH/LOW
  • Affichage d'Entrée : Affichage en temps réel des états des broches d'entrée
  • Valeurs Analogiques : Affiche les valeurs analogiques brutes pour les broches ADC

Modes de Broche

  • BT_PIN_OUTPUT (0) : Contrôle la sortie numérique — bascule depuis l'application
  • BT_PIN_INPUT (1) : Surveille l'entrée numérique ou analogique — affiche l'état actuel

Exemples de Programmation

Contrôle de Relais de Base

const int RELAY_1 = 16; const int RELAY_2 = 17; const int RELAY_3 = 18; const int RELAY_4 = 19; void setup() { pinMode(RELAY_1, OUTPUT); pinMode(RELAY_2, OUTPUT); pinMode(RELAY_3, OUTPUT); pinMode(RELAY_4, OUTPUT); bluetoothPins.enablePin(RELAY_1, BT_PIN_OUTPUT, "Light"); bluetoothPins.enablePin(RELAY_2, BT_PIN_OUTPUT, "Fan"); bluetoothPins.enablePin(RELAY_3, BT_PIN_OUTPUT, "Pump"); bluetoothPins.enablePin(RELAY_4, BT_PIN_OUTPUT, "Heater"); bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); Serial.print("Relay on pin "); Serial.print(pin); Serial.println(state ? " activated" : " deactivated"); }); }

Surveillance de Boutons et Commutateurs

const int BUTTON_PINS[] = {18, 19, 21, 22}; const char* BUTTON_NAMES[] = {"Btn1", "Btn2", "Btn3", "Btn4"}; const int NUM_BUTTONS = 4; int lastButtonStates[4] = {HIGH, HIGH, HIGH, HIGH}; void setup() { for (int i = 0; i < NUM_BUTTONS; i++) { pinMode(BUTTON_PINS[i], INPUT_PULLUP); bluetoothPins.enablePin(BUTTON_PINS[i], BT_PIN_INPUT, BUTTON_NAMES[i]); } bluetoothPins.onPinRead([](int pin) -> int { return digitalRead(pin); }); } void loop() { bluetoothServer.loop(); // Vérifier les changements d'état des boutons for (int i = 0; i < NUM_BUTTONS; i++) { int state = digitalRead(BUTTON_PINS[i]); if (state != lastButtonStates[i]) { lastButtonStates[i] = state; bluetoothPins.updatePinState(BUTTON_PINS[i], state); } } delay(10); }

Système Mixte Entrée/Sortie

void setup() { // Broches de sortie pour les actionneurs bluetoothPins.enablePin(2, BT_PIN_OUTPUT, "LED"); bluetoothPins.enablePin(16, BT_PIN_OUTPUT, "Relay"); // Broches d'entrée numériques pour les capteurs bluetoothPins.enablePin(18, BT_PIN_INPUT, "Motion"); bluetoothPins.enablePin(19, BT_PIN_INPUT, "Door"); // Broches d'entrée analogiques pour les capteurs bluetoothPins.enablePin(34, BT_PIN_INPUT, "Light"); bluetoothPins.enablePin(35, BT_PIN_INPUT, "Temp"); // Configurer le matériel pinMode(2, OUTPUT); pinMode(16, OUTPUT); pinMode(18, INPUT_PULLUP); pinMode(19, INPUT_PULLUP); bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); }); bluetoothPins.onPinRead([](int pin) -> int { if (pin == 34 || pin == 35) return analogRead(pin); return digitalRead(pin); }); }

Techniques de Programmation Avancées

Verrouillage de Sécurité

bool safetyEnabled = true; bluetoothPins.onPinWrite([](int pin, int state) { // Vérification de sécurité : ne pas permettre les sorties conflictuelles if (pin == 16 && state == HIGH) { // Vérifier si le verrouillage de sécurité permet ceci if (digitalRead(18) == LOW) { // Le commutateur de sécurité doit être engagé bluetoothPins.updatePinState(16, 0); // Rejeter la commande Serial.println("SAFETY: Operation blocked - safety switch off"); return; } } digitalWrite(pin, state); });

Arrêt Automatique Temporisé

unsigned long pinTimers[16] = {0}; unsigned long PIN_TIMEOUT = 300000; // 5 minutes bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); if (state == HIGH) { pinTimers[pin] = millis(); // Démarrer le minuteur } else { pinTimers[pin] = 0; // Effacer le minuteur } }); void loop() { bluetoothServer.loop(); // Vérifier les timeouts d'arrêt automatique for (int i = 0; i < 16; i++) { if (pinTimers[i] > 0 && millis() - pinTimers[i] >= PIN_TIMEOUT) { digitalWrite(i, LOW); pinTimers[i] = 0; bluetoothPins.updatePinState(i, 0); Serial.print("Auto-off: Pin "); Serial.println(i); } } delay(10); }

BLE vs Bluetooth Classique - Lequel Choisir ?

FonctionnalitéBLE (Esp32BLE_PinControl)Bluetooth Classique (Esp32Bluetooth_PinControl)
Support iOS? Oui? Non
Support Android? Oui? Oui
ConsommationFaiblePlus élevée
Portée~30-100m~10-100m
Débit de DonnéesPlus faiblePlus élevé
Appairage RequisNon (auto-connexion)Oui (appairage manuel)
Idéal PourAlimenté par batterie, multi-plateformeHaut débit, Android uniquement

Dépannage

Problèmes Courants

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

  • Assurez-vous que l'ESP32 est alimenté et que le sketch est téléversé
  • Pour BLE : Assurez-vous que le Bluetooth et la Localisation de votre téléphone sont activés
  • Pour Bluetooth Classique : Appairez d'abord l'appareil dans les paramètres Bluetooth du téléphone
  • Vérifiez que le bon schéma de partition est sélectionné (Huge APP)

2. Les broches n'apparaissent pas dans l'application

  • Assurez-vous que enablePin() est appelé avant la connexion Bluetooth
  • Vérifiez getEnabledPinCount() dans le Moniteur Série
  • Vérifiez que les numéros de broche sont entre 0 et 15

3. Les broches de sortie ne basculent pas

  • Vérifiez que le callback onPinWrite() appelle digitalWrite()
  • Vérifiez que les broches sont configurées comme BT_PIN_OUTPUT
  • Vérifiez les connexions matérielles

4. Les valeurs d'entrée ne se mettent pas à jour

  • Assurez-vous que updatePinState() est appelé lorsque les états changent
  • Vérifiez l'intervalle de polling dans la boucle
  • Pour les broches analogiques, ajustez le seuil de changement

5. Trop de broches causent des erreurs

  • Maximum 16 broches supportées (0-15)
  • Gardez les noms de broches courts pour éviter la troncature des messages
  • Utilisez des noms plus courts si vous obtenez des avertissements de troncature

6. Sketch trop volumineux / pas assez d'espace

  • Dans l'Arduino IDE, allez à Tools > Partition Scheme et sélectionnez "Huge APP (3MB No OTA/1MB SPIFFS)" ou "No OTA (Large APP)"
  • Le schéma de partition par défaut ne fournit que ~1.2MB pour le code de l'application, ce qui n'est pas suffisant pour les librairies Bluetooth
  • Ce réglage donne ~3MB en sacrifiant la partition OTA (mise à jour par air)

Conseils de Débogage

Ajoutez un débogage complet :

void debugPinConfig() { Serial.println("=== Pin Config Debug ==="); Serial.println("Enabled pins: " + String(bluetoothPins.getEnabledPinCount())); for (int i = 0; i < 16; i++) { if (bluetoothPins.isPinEnabled(i)) { Serial.print(" Pin " + String(i) + ": "); Serial.println(bluetoothPins.getPinMode(i) == BT_PIN_OUTPUT ? "OUTPUT" : "INPUT"); } } Serial.println("========================"); }

Idées de Projets

Domotique

  • Contrôleur d'interrupteur lumineux Bluetooth
  • Panneau de contrôle de relais multi-pièces
  • Ouvre-porte de garage
  • Contrôle de vannes d'irrigation de jardin

Projets de Sécurité

  • Moniteur de capteurs de portes et fenêtres
  • Notification de détecteur de mouvement
  • Système d'alarme Bluetooth
  • Panneau de contrôle d'accès

Projets Industriels

  • Contrôle de démarrage/arrêt de machine
  • Moniteur de réseau de capteurs
  • Contrôle de vannes et actionneurs
  • Panneau d'indicateurs de statut

Projets Éducatifs

  • Outil d'apprentissage d'électronique numérique
  • Exploration de broches GPIO
  • Test de circuits d'entrée/sortie
  • Contrôleur de projets breadboard

Intégration avec d'Autres Applications Bluetooth

Combiner avec Bluetooth Slider

Utilisez les broches numériques pour on/off et les sliders pour l'intensité PWM :

bluetoothPins.onPinWrite([](int pin, int state) { if (state == HIGH) { // Quand la broche est activée, appliquer le PWM contrôlé par slider analogWrite(pin, map(currentSlider1, 0, 100, 0, 255)); } else { analogWrite(pin, 0); } });

Combiner avec Bluetooth Monitor

Enregistrez les changements de broches dans le moniteur :

bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); bluetoothMonitor.send("Pin " + String(pin) + " -> " + String(state ? "ON" : "OFF")); });

Étapes Suivantes

Après avoir maîtrisé l'exemple Bluetooth Broches Numériques, essayez :

  1. Bluetooth Slider - Pour le contrôle PWM de type analogique
  2. Bluetooth Monitor - Pour déboguer les états des broches
  3. Bluetooth Table - Pour l'affichage structuré des données de broches
  4. Applications Bluetooth Multiples - Combiner le contrôle des broches avec d'autres fonctionnalités

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 !