/* Reflex test game with one button and one LED. 1. click button to start program (state 0) (led will stay one for 1 sec indicate you pressed the button) 2. wait three seconds 3. LED flashes on and off for 250 ms (state 2) 4. you press button as a response (state 3) if you press it fast enough (within 1 second), LED blinks quickly a few times if you press too slow, LED turns on, then fades Alice Nasto 10/2013 */ // set pin numbers: const int buttonPin = 3; // the number of the pushbutton pin const int ledPin = 7; // the number of the LED pin int state = 0; unsigned long gameStart = 0; unsigned long timePress = 0; int brightness = 255; // how bright the LED is int fadeAmount = 2; // how many points to fade the LED by int randNumber = 0; void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize the pushbutton pin as an input: pinMode(buttonPin, INPUT); } void loop(){ boolean buttonState = digitalRead(buttonPin); // reads if high or low switch(state){ case 0: if (buttonState == LOW){ // if buton is pressed state = 1; // for next time it loops, it will go to 1 digitalWrite(ledPin, HIGH); // turn LED on for 250 ms then turn it off delay(1000); digitalWrite(ledPin, LOW); } break; case 1: randNumber = random(1,10); delay(randNumber*1000); // have the delay time be a random duration between 1 and 10 s. digitalWrite(ledPin, HIGH); // turn LED on for 250 ms then turn it off delay(250); digitalWrite(ledPin, LOW); gameStart = millis(); state = 2; // next time it loops, it will go to 2 //} break; case 2: if (buttonState == LOW){ // check if button has been pressed timePress = (millis() - gameStart); // timePress is the amount of time after the gameStart if (timePress < 500){ // if the time that has passed is less than 500 ms, blink! you WIN! digitalWrite(ledPin, HIGH); // turn LED on for 250 ms then turn it off delay(250); digitalWrite(ledPin, LOW); delay(250); digitalWrite(ledPin, HIGH); // turn LED on for 250 ms then turn it off delay(250); digitalWrite(ledPin, LOW); delay(250); digitalWrite(ledPin, HIGH); // turn LED on for 250 ms then turn it off delay(250); digitalWrite(ledPin, LOW); delay(250); digitalWrite(ledPin, HIGH); // turn LED on for 250 ms then turn it off delay(250); digitalWrite(ledPin, LOW); delay(250); digitalWrite(ledPin, HIGH); // turn LED on for 250 ms then turn it off delay(250); digitalWrite(ledPin, LOW); }else { // have LED turn on then fade. You lose! while(brightness > 2){ analogWrite(ledPin, brightness); // change the brightness for next time through the loop: brightness = brightness - fadeAmount; // reverse the direction of the fading at the ends of the fade: if (brightness == 0 || brightness == 255) { fadeAmount = +fadeAmount ; brightness = 255; } // wait for 30 milliseconds to see the dimming effect delay(30); } } state = 0; // reset game and all the time counting variables gameStart = 0; timePress = 0; brightness = 255; digitalWrite(ledPin, LOW); // turn LED off after game } break; } }