#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int LEDPins[6] = {0, 4, 16, 17, 5, 18};
const int Buttons[6] = {12, 14, 27, 26, 25, 13};
const int Buzzer = 2;
const int Start_Button = 15;
const int time_limit = 1000; // in seconds
const int active_time = 1000;
const int buzzer_time = 200;
int timer, timer_start, LED_time;
int score, currentLED;
// RESET state
bool start = false;
bool finish = false;
void setup() {
Wire.begin(21, 22); // SDA, SCL
lcd.init();
lcd.backlight();
pinMode(Start_Button, INPUT_PULLUP);
pinMode(Buzzer, OUTPUT);
for (int i = 0; i < 6; i++){
pinMode(Buttons[i], INPUT_PULLUP);
pinMode(LEDPins[i], OUTPUT);
digitalWrite(LEDPins[i], LOW);
}
randomSeed(millis()); // for defining the seed as per the time returned by millis()
}
void loop() {
if (!start && !finish){
if (digitalRead(Start_Button) == LOW){
start_game();
}
}
else if (start){
LCD_update();
LED_update();
}
else if (finish){
if (digitalRead(Start_Button) == LOW){
finish = false; // back to RESET state
}
}
}
// start game (BUTTON PRESSED)
void start_game(){
timer_start = millis();
LED_time = millis();
timer = 30; // The game goes on for 30 seconds
score = 0;
start = true;
}
void end_game(){
start = false;
finish = true;
}
// timer handling
void LCD_update(){
if (millis() - timer_start < time_limit){
// displaying time remaining
lcd.setCursor(8, 0);
if (timer < 10){
lcd.print("TIME: 0");
} else {
lcd.print("TIME: ");
}
lcd.print(timer);
lcd.setCursor(0,1);
lcd.print("SCORE: ");
lcd.print(score);
}
timer--;
}
// random LED lighting
void LED_update(){
if (millis() - LED_time >= active_time){
LED_time = millis();
if (currentLED >= 0){
digitalWrite(LEDPins[currentLED], LOW); // reset the state back to all LOW
}
currentLED = random(0,6);
digitalWrite(LEDPins[currentLED], HIGH); // turn on the currentLED
}
}
// button checking
void click(){
click_time = millis();
if (digitalRead(Buttons[currentLED]) == LOW){
score++; // add to score
digitalWrite(LEDPins[currentLED] == LOW); // immediately turn off the LED
digitalWrite(Buzzer, HIGH);
}
if (millis() - click_time > buzzer_time){
digitalWrite(Buzzer, LOW);
}
}