Simon: Random Sequence
Part of the Projects section of Coddy's Arduino journey. Lesson 14 of 24.
Now the board takes its turn. The first time a button is let go, the game starts: the board picks four random colours, keeps them in an array, and plays them.
random(4) gives 0, 1, 2 or 3: one colour. A for loop fills the array. As in the reaction game, seed with micros() at the press, or every game plays the same colours:
randomSeed(micros());
for (int i = 0; i < 4; i++) {
sequence[i] = random(4);
}A second for loop plays the pattern: light a colour with its note, wait, turn it off, and wait again. The second wait matters when a colour comes twice: without it, red, red looks like one long red. The player only watches now, so delay() is fine.
for (int i = 0; i < 4; i++) {
lightOn(sequence[i]);
delay(400);
lightOff(sequence[i]);
delay(200);
}A bool called playing remembers that the game has started, so only the first press starts it.
Challenge
MediumMake the board play a pattern:
- add
int sequence[4];andbool playing = false; - when a button is let go and
playingisfalse: seed, fill the array withrandom(4), setplayingtotrue, and play the pattern - the pattern: wait 500 ms, then each colour with its note for 400 ms, and 200 ms of quiet after it
Afterwards the buttons light and play as before. Press Run, press a button, then Check.
Try it yourself
// One entry per colour: red, green, blue, yellow
const int ledPins[4] = {9, 10, 11, 12};
const int buttonPins[4] = {2, 3, 4, 5};
const int notes[4] = {262, 330, 392, 523}; // C, E, G and high C
const int buzzerPin = 8;
int lastState[4] = {HIGH, HIGH, HIGH, HIGH}; // each button's last reading
// Light colour i and play its note.
void lightOn(int i) {
digitalWrite(ledPins[i], HIGH);
tone(buzzerPin, notes[i]);
}
// Turn colour i off and stop the sound.
void lightOff(int i) {
digitalWrite(ledPins[i], LOW);
noTone(buzzerPin);
}
void setup() {
for (int i = 0; i < 4; i++) {
pinMode(ledPins[i], OUTPUT);
pinMode(buttonPins[i], INPUT_PULLUP);
}
}
void loop() {
for (int i = 0; i < 4; i++) {
int state = digitalRead(buttonPins[i]);
if (state == LOW && lastState[i] == HIGH) { // pressed
lightOn(i);
}
if (state == HIGH && lastState[i] == LOW) { // let go
lightOff(i);
}
lastState[i] = state;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Projects
Practice on your own: Arduino playground