/* timer_demo.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 1024/16000000 seconds, which is 64 usec. The SIG_OVERFLOW0 interrupt occurs every (1024*256)/16000000 = 0.0164 seconds. On each interrupt, the routine increments an internal counter ("counter"). When this counter reaches 61, the interrupt routine toggles PB0 and resets "counter". 61 * 0.0164 sec = 1 sec (approximately). So - the LED attached to PB0 flashes at a frequency of 0.5 Hz. Note that this approach allows "something else" to take an arbitrary amount of time. */ #include #include #include #include #include "oulib.h" // Global so that it can be used in the interrupt handler, but // initialized by the main routine. unsigned char counter; // Interrupt handler for TIMER0 overflow ISR(TIMER0_OVF_vect) { ++counter; if(counter == 61) { // Toggle output state every 61st interrupt: // This means on for ~ 1 second and then off for ~1 sec PORTB ^= 1; counter = 0; }; }; int main(void) { // Initialize I/O DDRB = 0xFF; PORTB = 0; // Initialize counter counter = 0; // Interrupt occurs every (1024*256)/16000000 = .0164 seconds timer0_config(TIMER0_PRE_1024); // Enable the timer interrupt timer0_enable(); // Enable global interrupts sei(); while(1) { // Do something else // Note that this does not have to worry at all about // timing with respect to toggling PB0 }; return(0); }