//--------------------------------------------------------------------// /* TIMER0 Interrupt Example template showing hooking the TIMER0 interrupt for our own uses. This routine uses TIMER0 to generate a periodic interrupt. TIMER0 is already being used for delay(), so this routine piggybacks off of it. The routine is low overhead and allows for periodic delays without the overhead of using delay(). The interrupt handler sets a flag (time) whenever the specified time interval has expired. The main routine (loop()) checks if the flag is true and takes some action. Note that the flag (time) has to be cleared (set to false) when processing the action. The template can easily be expanded to process multiple intervals by adding additional flags (e.g. time1, time2, ...) and counters (count1, count2, ... instead of count). To use it add the following to your program: 1. #define TIMER0_COUNT and interrupt handler stuff to your program. Set TIMER0_COUNT to the number of milliseconds of your periodic interval (e.g. repeat every 3 seconds => "const unsigned int TIMER0_COUNT = 3000;" 2. initialization (cli(); ... sei();) 3. time check (in loop()) to check time flag and do something. Note: You can do lots of other things as part of the repeating loop (loop()) while time check is in the loop. This routine dovetails nicely with a state machine. Author: Bruce Raymond Date: 27 Oct 2018 Revision: 1.0 */ //--------------------------------------------------------------------// //--------------------- add me ---------------------------------------// // *** Define the time interval in milliseconds *** const unsigned long TIMER0_COUNT = 500; // 500 msec timer interval // interrup handler - tacked onto the end of TIMER0 handler volatile bool time = false; ISR( TIMER0_COMPA_vect ) { static unsigned long count = 0; if ( ++count > TIMER0_COUNT ) { count = 0; time = true; // time is set to true every TIMER0_COUNT ms } // (time needs to be cleared in the main routine) } //--------------------------------------------------------------------// //--------------------------------------------------------------------// void setup() { Serial.begin( 115200 ); // not actually part of Timer0 stuff //--------------------- add me -------------------------------------// // *** TIMER0 initialization *** cli(); // turn off all interrupts TIMSK0 = 0; // turn off timer0 for lower jitter OCR0A = 0xBB; // arbitrary interrupt count TIMSK0 |= _BV( OCIE0A ); // piggy back onto interrupt sei(); // turn interrupts back on Serial.println( "starting up ..." ); } //--------------------------------------------------------------------// void loop() { //--------------------- add me -------------------------------------// // *** time check *** if ( time ) { time = false; // reset flag and wait for next interval // do something here Serial.println( "interrupt happened" ); // prints once every 'time' hit } // you can do other stuff here }