#include "sound.h"
// defining pins for LED, pushbutton and buzzer
const uint8_t ledPins[] = {13, 10, 11, 12};
const uint8_t buttonPins[] = {7, 4, 5, 6};
#define Buzzer 9
// To show game score:
const int LatchPin = A2;
const int DataPin = A0;
const int ClockPin = A1;
#define MaxIndex 100
//Sounds corresponding to each color
const int Tones[] = { NOTE_G3, NOTE_C4, NOTE_E4, NOTE_G5};
uint8_t gameSequence[MaxIndex] = {0};
uint8_t level = 0;
void setup()
{
Serial.begin(9600);
for (byte i = 0; i < 4; i++)
{
pinMode(ledPins[i], OUTPUT);
pinMode(buttonPins[i], INPUT_PULLUP);
}
pinMode(Buzzer, OUTPUT);
pinMode(LatchPin, OUTPUT);
pinMode(ClockPin, OUTPUT);
pinMode(DataPin, OUTPUT);
randomSeed(analogRead(A3));
}
//for displaying the score on 7-segmented LED display
uint8_t digitTable[] = {
0b11000000, //zero
0b11111001, //one
0b10100100, //two
0b10110000, //three
0b10011001, //four
0b10010010, //five
0b10000010, //six
0b11111000, //seven
0b10000000, //eight
0b10010000, //nine
};
void sendScore(uint8_t msb, uint8_t lsb)
{
digitalWrite(LatchPin, LOW);
shiftOut(DataPin, ClockPin, MSBFIRST, lsb);
shiftOut(DataPin, ClockPin, MSBFIRST, msb);
digitalWrite(LatchPin, HIGH);
}
void displayScore() {
int msb = level % 100 / 10;
int lsb = level % 10;
sendScore(digitTable[msb], digitTable[lsb]);
}
//play the arduino generated sequence
void LightandPlay(byte i) {
digitalWrite(ledPins[i], HIGH);
tone(Buzzer, Tones[i]);
delay(300);
digitalWrite(ledPins[i], LOW);
noTone(Buzzer);
}
void playSequence()
{
for (int i = 0; i < level; i++)
{
LightandPlay(gameSequence[i]);
delay(50);
}
}
//Compare users sequence with arduino's sequence
byte readButtons()
{
while (true)
{
for (byte i = 0; i < 4; i++)
{
byte buttonPin = buttonPins[i];
if (digitalRead(buttonPin) == LOW)
{return i;}
}
delay(1);
}
}
bool checkUserSequence()
{
for (int i = 0; i < level; i++)
{
byte expectedButton = gameSequence[i];
byte actualButton = readButtons();
LightandPlay(actualButton);
if (expectedButton != actualButton)
{return false;}
}
return true;
}
//Print the final score and play the game over sound
void gameOver()
{
Serial.print("Game over! your score: ");
Serial.println(level - 1);
level = 0;
delay(200);
tone(Buzzer, NOTE_A2);delay(650);
noTone(Buzzer);
displayScore();delay(1500);
}
//level up sound
void LevelUpSound()
{
tone(Buzzer, NOTE_G3);delay(150);
tone(Buzzer, NOTE_C4);delay(150);
tone(Buzzer, NOTE_E5);delay(150);
tone(Buzzer, NOTE_G5);delay(150);
tone(Buzzer, NOTE_GS5);delay(150);
noTone(Buzzer);
}
void loop()
{
displayScore();
gameSequence[level] = random(0, 4);
level++;
if (level >= MaxIndex)
{level = MaxIndex - 1;}
playSequence();
if (!checkUserSequence())
{gameOver();}
delay(300);
if (level > 0)
{LevelUpSound();
delay(300);}
}