/*
STM32 Reaction Timer Game (Group 6) - Wokwi, Nucleo C031C6
D10 -> 220R -> LED -> GND : reaction signal
D2 -> START button -> GND
D3 -> REACT button -> GND
Type 's' in the Serial Monitor to start a round as well.
*/
const int LED_PIN = D10;
const int START_PIN = D2;
const int REACT_PIN = D3;
enum State { IDLE, WAITING, SIGNAL_ON };
State state = IDLE;
unsigned long waitStart = 0, waitTime = 0, signalTime = 0, bestTime = 0;
int rounds = 0;
bool pressed(int pin) {
if (digitalRead(pin) == LOW) {
delay(20);
if (digitalRead(pin) == LOW) return true;
}
return false;
}
void waitRelease(int pin) {
while (digitalRead(pin) == LOW) { }
delay(30);
}
void printMenu() {
Serial.println();
Serial.println("=== STM32 REACTION TIMER ===");
Serial.println("Press START button (or send 's') to begin.");
}
void startRound() {
rounds++;
Serial.print("\nRound ");
Serial.println(rounds);
Serial.println("Get ready... wait for the LED!");
digitalWrite(LED_PIN, LOW);
waitTime = random(2000, 6000);
waitStart = millis();
state = WAITING;
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pinMode(START_PIN, INPUT_PULLUP);
pinMode(REACT_PIN, INPUT_PULLUP);
digitalWrite(LED_PIN, LOW);
randomSeed(analogRead(A0));
printMenu();
}
void loop() {
switch (state) {
case IDLE:
if (pressed(START_PIN)) {
waitRelease(START_PIN);
startRound();
} else if (Serial.available()) {
char c = Serial.read();
if (c == 's' || c == 'S') startRound();
}
break;
case WAITING:
if (pressed(REACT_PIN)) { // early press
waitRelease(REACT_PIN);
Serial.println("TOO EARLY! You pressed before the LED. Round restarted.");
delay(1000);
startRound();
break;
}
if (millis() - waitStart >= waitTime) { // delay over
digitalWrite(LED_PIN, HIGH);
signalTime = micros();
state = SIGNAL_ON;
}
break;
case SIGNAL_ON:
if (digitalRead(REACT_PIN) == LOW) {
unsigned long reaction = (micros() - signalTime) / 1000; // ms
digitalWrite(LED_PIN, LOW);
waitRelease(REACT_PIN);
Serial.print("Reaction time: ");
Serial.print(reaction);
Serial.println(" ms");
if (bestTime == 0 || reaction < bestTime) {
bestTime = reaction;
Serial.println("New best time!");
}
Serial.print("Best time: ");
Serial.print(bestTime);
Serial.println(" ms");
if (reaction < 200) Serial.println("Rating: Excellent!");
else if (reaction < 300) Serial.println("Rating: Good");
else if (reaction < 500) Serial.println("Rating: Average");
else Serial.println("Rating: Slow, try again");
state = IDLE;
printMenu();
}
break;
}
}Loading
st-nucleo-c031c6
st-nucleo-c031c6