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
| #include <Stepper.h>
// Définir le nombre de pas par tour
const byte pinLED = 3;
const byte pinCanon = 4;
Stepper monMoteur(200, 8, 9, 10, 11);
void gestionLed() {
static unsigned long chronoLed;
if (millis() - chronoLed >= 100) { // on change la LED toutes les 100ms
analogWrite(pinLED , 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();
}
}
void gestionMoteur() {
static unsigned long chronoMoteur;
if (millis() - chronoMoteur >= 5) { // on fait un pas toutes les 5 ms (200 pas x 5 ms = 1s == 1 tour par seconde)
monMoteur.step(1);
chronoMoteur = 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(5000); // 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);
chronoCanon = millis();
etatCanon = enTir;
}
break;
case enTir:
if (millis() - chronoCanon >= 500) { // on allume le canon 0.5 secondes (500 ms)
digitalWrite(pinCanon, LOW);
if (++nombreDeTirs >= 3) etatCanon = enInitialisation; // on a fini les 3 coups de canon
else {
duree = 1000; // 1s entre 2 coups de canon consécutifs
chronoCanon = millis();
etatCanon = enAttente;
}
}
break;
}
}
void setup() {
monMoteur.setSpeed(2000); // mettre une grande valeur
pinMode(pinLED, OUTPUT);
pinMode(pinCanon, OUTPUT);
}
void loop() {
gestionLed();
gestionMoteur();
gestionCanon();
} |
Partager