Rob Toulson / Mbed 2 deprecated PE_09-08_ReactionTime

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*Program Example 9.8: Tests reaction time, and demos use of Timer and Timeout functions
00002                                                                           */
00003 #include "mbed.h"
00004 #include <stdio.h>
00005 #include <stdlib.h>            //contains rand() function
00006 void measure ();
00007 Serial pc(USBTX, USBRX);
00008 DigitalOut led1(LED1);
00009 DigitalOut led4(LED4);
00010 DigitalIn responseinput(p5);  //the player hits the switch connected here to respond
00011 Timer t;                  //used to measure the response time
00012 Timeout action;               //the Timeout used to initiate the response speed test
00013 
00014 int main (){
00015   pc.printf("Reaction Time Test\n\r");
00016   pc.printf("------------------\n\r");
00017   while (1) {
00018     int r_delay;        //this will be the “random” delay before the led is blinked
00019     pc.printf("New Test\n\r");
00020     led4=1;                      //warn that test will start
00021     wait(0.2);
00022     led4=0; 
00023     r_delay = rand() % 10 + 1;  // generates a pseudorandom number range 1-10
00024     pc.printf("random number is %i\n\r", r_delay);  // allows test randomness; 
00025                                                     //removed for normal play
00026     action.attach(&measure,r_delay); // set up Timeout to call measure()
00027                                                                  // after random time
00028     wait(10);      //test will start within this time, and we then return to it
00029    }
00030 }
00031 
00032 void measure (){      // called when the led blinks, and measures response time    
00033   if (responseinput ==1){                            //detect cheating!
00034     pc.printf("Don't hold button down!");
00035   }
00036   else{
00037     t.start();             //start the timer
00038     led1=1;                //blink the led
00039     wait(0.05);
00040     led1=0;
00041     while (responseinput==0) {
00042       //wait here for response
00043     }
00044     t.stop();                       //stop the timer once response detected
00045     pc.printf("Your reaction time was %f seconds\n\r", t.read());
00046     t.reset();   
00047   }
00048 }
00049