#define BUTTON_R 12
#define BUTTON_B 13
#define BUTTON_G 14
#define BUTTON_Y 15
#define LED_R 19
#define LED_B 18
#define LED_G 17
#define LED_Y 16
#define BUZZER 20
class LIGHTS {
private:
int pin;
bool lit;
int LedPin;
int freq;
public:
LIGHTS(int p, int f )
{
freq = f;
LedPin = p;
lit = false;
pinMode(LedPin, OUTPUT);
};
void ControlLED()
{
if (lit == true){
digitalWrite(LedPin, HIGH);
tone(BUZZER, freq);
}
else{
digitalWrite(LedPin, LOW);
tone(BUZZER, 0);
}
}
void flash()
{
this->on();
this->ControlLED();
delay(500);
this->off();
this->ControlLED();
delay(500);
}
void on() { lit = true; }
void off() { lit = false; }
};
LIGHTS Red = LIGHTS(LED_R, 196);
LIGHTS Green = LIGHTS(LED_G, 262);
LIGHTS Blue = LIGHTS(LED_B, 330);
LIGHTS Yellow = LIGHTS(LED_Y, 784);
LIGHTS Colours[4] = { Red, Green, Blue, Yellow };
int start[16] = {300,500,0,200,300,500,0,200,300,500,0,200,750,1000,0,0};
int Buttons[4] = {BUTTON_R, BUTTON_G, BUTTON_B, BUTTON_Y};
int sequence[50];
int level;
int GameOver = 1;
void flashAll(){
for(int i=0; i<4; i++){
digitalWrite(LED_Y+i, HIGH);
delay(100);
digitalWrite(LED_Y+i, LOW);
delay(100);
}
}
int getButton() {
int BUTTON = -1;
if (digitalRead (BUTTON_R) == LOW)
BUTTON = 0;
if (digitalRead(BUTTON_G) == LOW)
BUTTON = 1;
if (digitalRead(BUTTON_B) == LOW)
BUTTON = 2;
if (digitalRead(BUTTON_Y) == LOW)
BUTTON = 3;
return BUTTON;
}
void playTone(int t[], int size){
printf("%d \n",size);
for (int i=0; i<=size; i+=2){
tone(BUZZER,t[i]);
delay(t[i+1]);
}
}
void gameOver(){
if (GameOver != 0){
while(getButton() == -1){
flashAll();
}
GameOver = 0;
level = 0;
delay(1000);
srand(millis());
playTone(start,sizeof(start)/sizeof(start[0]));
}
}
void PlayerInput(){
int press = -1;
for (int playRound = 1; playRound < level; playRound++) {
do {
delay(1);
press = getButton();
} while (press == -1);
Colours[press].flash();
if (sequence[playRound] != press) {
GameOver = 1;
break;
}
}
delay(1000);
}
void NextColour()
{
int nextC = rand() % 4;
level++;
sequence[level] = nextC;
for (int i = 1; i < level; i++) {
Colours[sequence[i]].flash();
}
}
void InitGame() {
level = 0;
for (int i = 0; i < 4; i++){
Colours[i].ControlLED();
}
}
void setup() {
Serial1.begin(115200);
delay(2000);
for (int i = 0; i < 4;i++){
pinMode(Buttons[i], INPUT_PULLUP);
}
}
void loop()
{
InitGame();
gameOver();
while(true){
NextColour();
PlayerInput();
gameOver();
}
}