/* timer_demo3.c Use of timer0 to produce a regular event (in this example, the toggling of an output pin). This happens while we also do "something else". With a 16MHz clock, timer0 increments every 64/16000000 seconds, which is 4 usec. The SIG_OVERFLOW0 interrupt occurs every (64*256)/16000000 = 0.001 seconds. On each interrupt, the routine increments an internal counter ("counter"). When this counter reaches 26, the interrupt routine sets trigger_flag and resets "counter". 26 * 0.0010 sec = 26.6 msec. So - trigger_flag is set to 1 at 37.561 Hz. */ #include #include #include #include #include "oulib.h" // Global so that it can be used in the interrupt handler, but // initialized by the main routine. volatile uint8_t trigger_flag; // Interrupt handler for TIMER0 overflow ISR(TIMER0_OVF_vect) { static unsigned char counter = 0; ++counter; if(counter == 26) { // Toggle output state every 61st interrupt: // This means on for ~ 1 second and then off for ~1 sec trigger_flag = 1; counter = 0; }; }; int main(void) { // Interrupt occurs every (64*256)/16000000 = .0010 seconds timer0_config(TIMER0_PRE_64); // Enable the timer interrupt timer0_enable(); // Enable global interrupts sei(); while(1) { while(trigger_flag == 0) {} trigger_flag = 0; // Sample from the sensors (result is 37.5601 Hz) }; return(0); }