Skip to content

Instantly share code, notes, and snippets.

@lewayotte
Last active November 10, 2016 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lewayotte/9b0da4a892180f8350762b73c3b74924 to your computer and use it in GitHub Desktop.
Save lewayotte/9b0da4a892180f8350762b73c3b74924 to your computer and use it in GitHub Desktop.
Reaction Game for Arduino using LCD, LED, and Switch
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);
const int switchPin = 8;
int switchStatus = LOW;
const int ledPin = 7;
int time = 0;
bool startPhase1 = false;
int randomStart = 0;
bool startPhase2 = false;
bool gameComplete = false;
bool hasWarned = false;
void setup() {
pinMode(switchPin, INPUT);
pinMode(ledPin, OUTPUT);
resetGame();
}
void loop() {
int currentTime = millis();
switchStatus = digitalRead(switchPin);
if ( gameComplete && 5000 <= currentTime - time ) {
resetGame();
} else if ( startPhase1 && !startPhase2 && !gameComplete && switchStatus == LOW && hasWarned ) {
lcd.clear();
hasWarned = false;
} else if ( startPhase1 && !startPhase2 && !gameComplete && switchStatus == HIGH ) {
if ( !hasWarned ) {
lcd.clear();
lcd.begin(16, 2);
lcd.print( "Stop holding the" );
lcd.setCursor(0,1);
lcd.print( "button, cheater!" );
}
hasWarned = true;
restartPhase1(currentTime);
delay(500);
} if ( startPhase1 && startPhase2 && !gameComplete && switchStatus == HIGH ) {
lcd.clear();
lcd.begin(16, 2);
lcd.print( "Reaction Time:" );
lcd.setCursor(0,1);
float timeDiff = ( currentTime - time ) / 1000.00;
lcd.print( String( String( timeDiff, 3 ) + " seconds" ) );
gameComplete = true;
time = currentTime;
} else if ( startPhase1 && !startPhase2 && !gameComplete && randomStart <= ( currentTime - time ) ) {
startPhase2 = true;
digitalWrite(ledPin, HIGH);
time = currentTime;
} else if ( !startPhase1 && !startPhase2 && !gameComplete && switchStatus == HIGH ) {
restartPhase1(currentTime);
lcd.clear();
delay(500);
}
}
void restartPhase1(int currentTime) {
startPhase1 = true;
randomStart = random(1500, 5000);
time = currentTime;
}
void resetGame() {
digitalWrite(ledPin, LOW);
lcd.clear();
lcd.begin( 16, 2 );
lcd.print("Push button");
lcd.setCursor(0, 1);
lcd.print("to start!");
randomSeed(analogRead(0));
startPhase1 = false;
startPhase2 = false;
gameComplete = false;
hasWarned = false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment