| 12
 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
 
 | const byte pinlanceflamme = 5;
const byte pinCanon = 3;
const byte pinmarcheur = 6;
 
void gestionLed() {
  static unsigned long chronoLed;
  if (millis() - chronoLed >= 100) { // on change la LED toutes les 100ms
    analogWrite(pinlanceflamme , random(120) + 250); // notez que l'on passe normalement une valeur entre 0 et 255 donc random(120) + 250 va déborder et être tronqué
    chronoLed = millis();
  }
}
 
enum : byte {enInitialisation, enAttente, enTir} etatCanon = enInitialisation;
void gestionCanon() {
  static unsigned long chronoCanon;
  static unsigned long duree;
  static byte nombreDeTirs;
 
  switch (etatCanon) {
    case enInitialisation:
      duree = 5000 + random(500); // on génére une attente aléatoire entre 5 et 10s
      chronoCanon = millis();
      etatCanon = enAttente;
      nombreDeTirs = 0;
      break;
 
    case enAttente:
      if (millis() - chronoCanon >= duree) { // l'attente est finie
        digitalWrite(pinCanon, HIGH);
        digitalWrite(pinmarcheur, HIGH);
        chronoCanon = millis();
        etatCanon = enTir;
      }
      break;
 
    case enTir:
      if (millis() - chronoCanon >= 30) { // on allume le canon 0.5 secondes (500 ms)
        digitalWrite(pinCanon, LOW);
        digitalWrite(pinmarcheur, LOW);
        if (++nombreDeTirs >= 20) etatCanon = enInitialisation; // on a fini les 3 coups de canon
        else {
          duree = 15; // 1s entre 2 coups de canon consécutifs
          chronoCanon = millis();
          etatCanon = enAttente;
        }
      }
      break;
  }
}
 
void setup() {
 
  pinMode(pinlanceflamme, OUTPUT);
  pinMode(pinCanon, OUTPUT);
  pinMode(pinmarcheur, OUTPUT);
}
 
void loop() {
  gestionLed();
  gestionCanon();
} | 
Partager