Code
Code
The Simon Says game flashes a pattern using LED lights, then the player must
repeat the pattern.
This sketch was written by SparkFun Electronics, with lots of help from the
Arduino community.
This code is completely free for any use.
//set the pins where the buttons, LEDs and buzzer connect
int button[] = {2, 4, 6, 8}; //red is button[0], yellow is button[1], green is
button[2], blue is button[3]
int led[] = {3, 5, 7, 9}; //red is led[0], yellow is led[1], green is led[2],
blue is led[3]
int tones[] = {262, 330, 392, 494}; //tones to play with each button (c, e, g, b)
int roundsToWin = 10; //number of rounds the player has to play before they
win the game (the array can only hold up to 16 rounds)
int buttonSequence[16]; //make an array of numbers that will be the sequence
that the player needs to remember
void setup() {
//set all of the button pins to input_pullup (use the built-in pull-up resistors)
pinMode(button[0], INPUT_PULLUP);
pinMode(button[1], INPUT_PULLUP);
pinMode(button[2], INPUT_PULLUP);
pinMode(button[3], INPUT_PULLUP);
void loop() {
if (gameStarted == false) { //if the game hasn't started yet
startSequence(); //flash the start sequence
roundCounter = 0; //reset the round counter
delay(1500); //wait a second and a half
gameStarted = true; //set gameStarted to true so that this sequence
doesn't start again
}
//then start going through the sequence one at a time and see if the user presses
the correct button
for (int i = 0; i <= roundCounter; i++) { //for each button to be pressed in the
sequence
while (gameStarted == true) { //loop until the player presses a button or the
time limit is up (the time limit check is in an if statement)
if (gameStarted == true) {
roundCounter = roundCounter + 1; //increase the round number by 1
//----------FUNCTIONS------------
//FLASH LED
void flashLED (int ledNumber) {
digitalWrite(led[ledNumber], HIGH);
tone(buzzerPin, tones[ledNumber]);
}
//START SEQUENCE
void startSequence() {
//WIN SEQUENCE
void winSequence() {
gameStarted = false; //reset the game so that the start sequence will play
again.
//LOSE SEQUENCE
void loseSequence() {
gameStarted = false; //reset the game so that the start sequence will play
again.
}