Skip to content

Instantly share code, notes, and snippets.

@greed9
Last active July 8, 2025 20:27
Show Gist options
  • Save greed9/8d8eb2469d3ef55781d1ba9f468ec6d5 to your computer and use it in GitHub Desktop.
Save greed9/8d8eb2469d3ef55781d1ba9f468ec6d5 to your computer and use it in GitHub Desktop.
Simple reaction timer app using switch and interrupts
// *****************************************
// Reaction timer using interrupt
// *****************************************
#define BUTTON_PIN 2
#define LED_PIN 8
// This must be declared volatile since it is accessed from
// the ISR and from loop()
//https://en.wikipedia.org/wiki/Volatile_(computer_programming)
static volatile int isr_counter = 0 ;
// ISR - execution saves state and jumps here when switch closed
void countBounces( void )
{
isr_counter ++ ;
}
void setup() {
Serial.begin( 9600 ) ;
Serial.println(F("START " __FILE__ " from " __DATE__ "\r\n" ));
pinMode( BUTTON_PIN, INPUT ) ;
pinMode( LED_PIN, OUTPUT ) ;
// Arduino function that sets up the ISR
// Note the use of trhe RISING keyword - why?
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), countBounces, RISING ) ;
Serial.println( "starting") ;
digitalWrite( LED_PIN, LOW ) ;
}
void loop() {
// copy isr variable into local -- this requirement may be a bug
int count = isr_counter ;
int reaction_time = 0 ;
isr_counter = 0 ;
// kill a random amount of time before starting
long raw_time_value = random() ;
int delay_milliseconds = map( raw_time_value, 0, RANDOM_MAX, 500, 5000) ;
delay( delay_milliseconds ) ;
// Go!
digitalWrite( LED_PIN, HIGH ) ;
long start_time = millis ( ) ;
// Loop waiting for ISR to set isr_counter to non-zero
while( !isr_counter ) { ; }
// Stop!
// compute duration
reaction_time = millis ( ) - start_time ;
digitalWrite( LED_PIN, LOW ) ;
Serial.println( reaction_time ) ;
delay( 5000 ) ;
//Serial.println( count ) ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment