Ce projet consistait à créer un dispositif qui génère un chiffre entre 1 et 4 à l’aide d’un bouton. En appuyant sur le bouton, les led clignotent puis s’allument aléatoirement. En fonction du chiffre (soit 1 ; 2 ; 3 ou 4), le buzzer émet un son. On peut recommencer en appuyant sur le bouton.
// base du code : https://create.arduino.cc/projecthub/EvdS/led-dice-885cf1?ref=tag&ref_id=games&offset=14
#define DEBUG 0
int first = 2;
int second = 3;
int third = 4;
int fourth = 5;
int buzzer = 8;
int button = 12;
int pressed = 0;
void setup() {
for (int i=first; i<=fourth; i++) {
pinMode(i, OUTPUT);
}
pinMode(button, INPUT);
randomSeed(analogRead(0));
#ifdef DEBUG
Serial.begin(9600);
#endif
}
void buildUpTension() {
for (int i=first; i<=fourth; i++) {
if (i!=first) {
digitalWrite(i-1, LOW);
}
digitalWrite(i, HIGH);
delay(100);
}
for (int i=fourth; i>=first; i--) {
if (i!=fourth) {
digitalWrite(i+1, LOW);
}
digitalWrite(i, HIGH);
delay(100);
}
}
void showNumber(int number) {
digitalWrite(first, HIGH);
if (number >= 2) {
digitalWrite(second, HIGH);
tone(buzzer, 98, 100);
delay(10);
}
if (number >= 3) {
digitalWrite(third, HIGH);
tone(buzzer, 130, 100);
delay(10);
}
if (number >= 4) {
digitalWrite(fourth, HIGH);
tone(buzzer, 294, 100);
delay(10);
}
}
int throwDice() {
int randNumber = random(1,5);
#ifdef DEBUG
Serial.println(randNumber);
#endif
return randNumber;
}
void setAllLEDs(int value) {
for (int i=first; i<=fourth; i++) {
digitalWrite(i, value);
}
}
void loop() {
pressed = digitalRead(button);
if (pressed == HIGH) {
setAllLEDs(LOW);
buildUpTension();
int thrownNumber = throwDice();
showNumber(thrownNumber);
}
}