1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| const byte pinLedGauche = 10;
const byte pinLedDroite = 11;
const byte pinReedGauche = 2;
const byte pinReedDroite = 3;
const unsigned long attente = 20ul; // temps d'attente entre 2 gradations
const byte maxLuminosite = 160; // luminosité max des LEDs
enum t_etat : byte {ETEINTE, GRADATION, ALLUMEE}; // les états possibles de notre LED
const byte PORTE_FERMEE = LOW;
const byte PORTE_OUVERTE = HIGH;
// Notre système décrit une porte instrumentée, on regroupe tout ce qui est nécessaire pour une porte
struct t_porte {
const byte pinLed; // pin --- R 220Ω ---- GND
const byte pinReed; // le switch dispose d'un pull down externe. LOW veut dire porte fermée, HIGH porte ouverte
t_etat etatLed;
byte etatPorte;
byte gradation;
byte unsigned long chrono;
};
t_porte portes[] = {
{pinLedDroite, pinReedDroite, ETEINTE, PORTE_FERMEE, 0, 0}, // la porte de droite
{pinLedGauche, pinReedGauche, ETEINTE, PORTE_FERMEE, 0, 0} // la porte de gauche
};
const byte nombreDePortes = sizeof portes / sizeof portes[0];
void testerPorte(t_porte& unePorte)
{
// on regarde l'état de la porte
byte etat = digitalRead(unePorte.pinReed);
if (unePorte.etatPorte != etat) { // Si l'état a changé
unePorte.etatPorte = etat; // on mémorise le nouvel état
if (unePorte.etatPorte == PORTE_FERMEE) { // on vient de fermer la porte, on éteint direct
digitalWrite(unePorte.pinLed, LOW);
unePorte.etatLed = ETEINTE;
} else { // on vient d'ouvrir la porte, on lance la gradation
unePorte.gradation = 0;
unePorte.chrono = millis();
unePorte.etatLed = GRADATION;
}
} else { // la porte est restée dans le même état
if (unePorte.etatLed == GRADATION) // si on était en mode gradation
if (millis() - unePorte.chrono >= attente) { // et que le delta T s'est écoulé
unePorte.gradation++; // alors on change la luminosité
analogWrite(unePorte.pinLed, unePorte.gradation);
unePorte.chrono = millis();
if (unePorte.gradation >= maxLuminosite) unePorte.etatLed = ALLUMEE; // on teste si on a fini
}
}
}
void setup()
{
for (byte i = 0; i < nombreDePortes; i++) {
pinMode(portes[i].pinLed, OUTPUT);
pinMode(portes[i].pinReed, OUTPUT);
}
}
void loop()
{
for (byte i = 0; i < nombreDePortes; i++) testerPorte(portes[i]);
} |
Partager