//////////////////////////////////////////// code machine à états - réponse post #66 //////////////////
////////////////////////////////////////////////////////// Code sous VScode - platformIO
// tuto de @J-M-L : https://forum.arduino.cc/t/programmation-automate-fini-machine-a-etat/452532 //////
// syntaxe tableaux : https://plaisirarduino.fr/tableau-de-donnees/
// switch case sur locoduino : https://www.locoduino.org/spip.php?article23
// Sur le forum : https://forum.arduino.cc/t/machine-a-etat-ou-pas/1123156
// Wokwi de @philippe86220 : https://wokwi.com/projects/364043838727653377
// Article pullup locoduino : https://www.locoduino.org/spip.php?article122
#include <Arduino.h>
#define BOUTON_APPUYE LOW // etats du BP, inversés car pullup
#define BOUTON_RELACHE HIGH
enum { REPOS, ETAT_V, ETAT_VJ, ETAT_VJO, ETAT_VJOR } etatCourant ; // enum états
const byte pinLED[4] = {11, 10, 9, 8} ; // tableau de pinLED
const byte pinBtn = 12 ; // BP sur la D12
void toutEteint()
{
for(int i = 0; i < 4; i++) {
digitalWrite(pinLED[i], LOW) ;
}
etatCourant = REPOS;
}
void setup() // setup
{
Serial.begin(115200);
pinMode(pinBtn, INPUT_PULLUP);
for ( int a = 0; a < 4; a++ ) {
pinMode(pinLED[a], OUTPUT) ;
}
etatCourant = REPOS ;
}
void loop() // loop
{
if (digitalRead(pinBtn) == BOUTON_APPUYE)
{
///////////////////////////////////////////////// switch case avec les états possibles //////
switch (etatCourant )
{
case REPOS : // on était au repos et on a un appui, on allume la verte
digitalWrite(pinLED[0], HIGH);
etatCourant = ETAT_V ;
Serial.println("1 LED allumee") ;
break;
case ETAT_V : // on était led verte allumée et on a un appui, on allume la jaune
digitalWrite(pinLED[1], HIGH); // LED jaune alimentée
etatCourant = ETAT_VJ;
Serial.println("2 LEDs allumees") ;
break;
case ETAT_VJ: // vert et jaune allumées, on a un appui, on allume la orange
digitalWrite(pinLED[2], HIGH); // LED orange alimenté
etatCourant = ETAT_VJO; // on note le nouvel état de notre système
Serial.println("3 LEDs allumees") ;
break;
case ETAT_VJO :// vert, orange et jaune allumées, on a un appui, on allume la rouge
digitalWrite(pinLED[3], HIGH); // LED rouge alimentée
etatCourant = ETAT_VJOR; // on note le nouvel état de notre système
Serial.println("4 LEDs allumees") ;
break;
case ETAT_VJOR : // tout était allumé, on a un appui, on retourne au repos
toutEteint() ; // on retourne à l'état initial
etatCourant = REPOS ;
Serial.println("tout est eteint") ;
break ;
default:
Serial.print("erreur etat imprevu !") ;
}
delay(200); // On attend 200 mS
// si on appuie sur le BP, on rentre dans la boucle, et on en sort au relachement du bouton
while (digitalRead(pinBtn) == BOUTON_APPUYE){;}
//
delay(200); // on re-attend 200 mS, si il y a un rebond juste après la boucle, il n'est pas pris en compte
}
// retour au test if au début de la loop
}