LED clignotante
J’ai parcouru différents tutoriaux pour débutants pour l’Arduino (ou l’ESP32). Généralement, nous y retrouvons une explication théorique sur l’électricité (les électrons, le sens “naturel” et “conventionel”, la loi d’Ohm, … ) puis des montages simples : une LED, un bouton, …
Globalement, c’est assez similaire.
Toutefois, j’ai bien aimé celui de ESP32I/O où les exemples sont un peu plus nombreux. Il propose notament de faire clignoter une LED tout en faisant tourner le script pour d’autres fonctions (voir LED Blink without delay)
Le site reprend également l’exemple de la LED qui reste allumée tant que j’appuie Button toggle LED.
Quid si j’appuie sur le boutton et que la LED clignote jusqu’à ce que je ré-appuie sur le boutton ? Ci-dessous un petit exemple de programme qui le permettra :
#define LED_PIN 26 // ESP32 pin GPIO26 connected to LED
#define BUTTON_PIN 25 // ESP32 pin GPIO25 connected to button
#define BLINK_INTERVAL 1000 // interval at which to blink LED (milliseconds)
// Variables will change:
int ledState = LOW; // ledState used to set the LED
int previousButtonState = LOW; // will store last time button was updated
int blinking = LOW; // store status of LED (must LED blink or not)
unsigned long previousMillis = 0; // will store last time LED was updated
void setup() {
Serial.begin(9600);
// set the digital pin as output:
pinMode(LED_PIN, OUTPUT);
// set the digital pin as an input:
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop() {
// check to see if it's time to blink the LED; that is, if the difference
// between the current time and last time you blinked the LED is bigger than
// the interval at which you want to blink the LED.
unsigned long currentMillis = millis();
// check button state's change
int currentButtonState = digitalRead(BUTTON_PIN);
if (currentMillis - previousMillis >= BLINK_INTERVAL && blinking == HIGH) {
// if the LED is off turn it on and vice-versa:
ledState = (ledState == LOW) ? HIGH : LOW;
// set the LED with the ledState of the variable:
digitalWrite(LED_PIN, ledState);
// save the last time you blinked the LED
previousMillis = currentMillis;
} else if (currentMillis - previousMillis >= BLINK_INTERVAL && blinking == LOW){
// if the LED is off turn it on and vice-versa:
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(LED_PIN, ledState);
// save the last time you blinked the LED
previousMillis = currentMillis;
}
if (currentButtonState != previousButtonState ) {
// print out the state of the button:
Serial.println(currentButtonState);
// save the last state of button
previousButtonState = currentButtonState;
if (previousButtonState == HIGH){
blinking = (blinking == LOW) ? HIGH : LOW;
}
Serial.println(blinking);
}
// DO OTHER WORKS HERE
}