Simon: Buttons and Notes
Part of the Projects section of Coddy's Arduino journey. Lesson 13 of 24.
Simon is a memory game: the board plays a pattern of coloured lights and notes, and you repeat it on the buttons. Each round the pattern grows by one, until you make a mistake. There are four colours, each with a button, an LED and a note.
With four of everything, arrays keep the sketch short. Entry 0 of every array is red, 1 is green, 2 is blue and 3 is yellow, so one number, i, names a colour everywhere:
const int ledPins[4] = {9, 10, 11, 12};
const int buttonPins[4] = {2, 3, 4, 5};
const int notes[4] = {262, 330, 392, 523};A for loop checks all four buttons. Act at two moments: a button goes down (LOW now, HIGH last time) and comes back up (HIGH now, LOW last time). The array lastState keeps each button's last reading. Later steps count a press when the button comes back up. These buttons do not bounce, so the edge checks are enough.
Challenge
MediumMake the four colours play:
- in
setup(), aforloop makes the LED pins outputs and the button pinsINPUT_PULLUP - when button
igoes down, lightledPins[i]and playnotes[i]on pin 8 - when it comes back up, turn the LED off and call
noTone()
Press Run, play the buttons, 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
void setup() {
// LEDs are outputs, buttons are INPUT_PULLUP
}
void loop() {
// for each button: when it goes down, light its LED and play its note;
// when it comes back up, turn them off
}
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