User:Fabien Labeyrie/Jacques a dit
Jacques a dit
The idea is to work with inputs and outputs of Arduino to make a Simon says kind of game.
How does it work ?
Technologies involved
Steps
- We need a board with a push button and a speaker.
- The code uses two while loops, constantly checking if the button is pressed, for how long, and launching a timeout during the waiting loop, in order to play the sequence after 5 seconds of wait.
Source code
const int buttonPin = 7;
int buttonState = 0;
int value1;
int value2;
int interval;
int pattern[100];
int i = 0;
int j = 0;
int wfp_start;
void setup() {
// 9600 is the frequency that will be used by the monitor
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
void loop(){
while (1) {
// State : WAIT FOR PRESS
wfp_start = millis();
while (digitalRead(buttonPin) == LOW && (millis() - wfp_start < 5000 )) {
// Do nothing the button isn't pressed
}
// Act as a timeout. Above 5 sec, we exit the WAIT loop and PLAY
if ((millis() - wfp_start >= 5000 )) break;
// State : WAIT FOR RELEASE
value1 = millis();
while (digitalRead(buttonPin) == HIGH) {
// Play tone when the button is pressed
tone(8, 100, 5);
}
value2 = millis();
interval = value2 - value1;
pattern[i]= interval;
Serial.println(pattern[i]);
// This will be used to simplify the values stored in the array
if (pattern[i] < 100) pattern[i] = 100;
else if (pattern[i] > 99 && pattern [i] < 200) pattern[i] = 200;
else if (pattern[i] > 199 && pattern [i] < 300) pattern[i] = 300;
else pattern[i] = 400;
Serial.println(" pattern : ");
Serial.println(pattern[i]);
i++;
}
// State : PLAY
while (j < i) {
tone(8, 100, pattern[j]);
Serial.println("Pattern plays");
j++;
}
}