/*
Arduino | coding-help
Guh — 4:27 PM Monday, January 5, 2026
changed the code of my reaction time tester but i encountered 2 problems.
-Button_state stops reading after green_led has been turned on
-reaction_time is constantly being updated
Does anyone know how to make it constantly read Button_state and prevent reaction_time from updating?
*/
#include <LiquidCrystal.h>
// pin constants
const int BUTTON_PIN = 4;
const int GRN_LED_PIN = 5;
const int RED_LED_PIN = 6;
const int RS = 12;
const int EN = 11;
const int D4 = 10;
const int D5 = 9;
const int D6 = 8;
const int D7 = 7;
enum {
SHOW_START,
WAIT_START,
SHOW_INSTRUCTIONS,
RANDOM_WAIT,
WAIT_REACTION,
SHOW_RESULT,
WAIT_RESULT
};
int state = 0;
int oldBtnState = 1; // INPUT_PULLUP idles HIGH
unsigned long random_wait = 0;
unsigned long random_time = 0;
unsigned long start_time = 0;
unsigned long end_time = 0;
unsigned long reaction_time = 0;
LiquidCrystal lcd(RS, EN, D4, D5, D6, D7);
void checkButton() {
int btnState = digitalRead(BUTTON_PIN); // read pin
if (btnState != oldBtnState) { // if it changed
oldBtnState = btnState; // remember for next time
if (btnState == LOW) { // if just pressed do stuff
lcd.clear();
state++;
if (state == 7) state = 0;
showState();
}
delay(20); // short debounce delay
}
}
void randomWait() {
if (millis() - random_time >= random_wait) {
digitalWrite(GRN_LED_PIN, HIGH);
digitalWrite(RED_LED_PIN, LOW);
start_time = millis();
state++;
showState();
}
}
void showInstructions() {
lcd.setCursor(2, 0);
lcd.print("Wait for the");
lcd.setCursor(3, 1);
lcd.print("green light");
random_wait = random(1000, 3001);
random_time = millis();
state++;
showState();
}
void showResult() {
end_time = millis();
reaction_time = end_time - start_time;
lcd.setCursor(1, 0);
lcd.print("Your time is:");
lcd.setCursor(5, 1);
lcd.print(reaction_time);
lcd.print(" ms");
digitalWrite(GRN_LED_PIN, LOW);
digitalWrite(RED_LED_PIN, LOW);
state++;
showState();
}
void showSplash() {
lcd.setCursor(1, 0);
lcd.print("Reaction Time");
lcd.setCursor(2, 1);
lcd.print("Tester V1.0");
delay(2000);
lcd.clear();
}
void showStart() {
lcd.setCursor(2, 0);
lcd.print("Press button");
lcd.setCursor(4, 1);
lcd.print("to start");
digitalWrite(GRN_LED_PIN, LOW);
digitalWrite(RED_LED_PIN, HIGH);
state++;
showState();
}
void showState() {
Serial.print("State: ");
Serial.println(state);
}
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(GRN_LED_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
showSplash();
showState();
}
void loop() {
checkButton();
switch (state) {
case (SHOW_START):
showStart();
break;
case (WAIT_START):
break;
case (SHOW_INSTRUCTIONS):
showInstructions();
break;
case (RANDOM_WAIT):
randomWait();
break;
case (WAIT_REACTION):
break;
case (SHOW_RESULT):
showResult();
break;
case (WAIT_RESULT):
break;
default:
Serial.println("No case matches...");
}
}