/* timer_demo2.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. When timer0 reaches 156, a counter is incremented. This increment happens 64 usec * 156 = 9984 usec, which is approximately 10ms. Once the counter reaches 50, the state of PB0 is toggled (so we flash the LED connected to PB0 at 1 Hz. Note that this approach relies on "something else" not taking too long. */ #include #include #include #include #include "oulib.h" int main(void) { unsigned char counter; // Initialize I/O DDRB = 0xFF; PORTB = 0; timer0_config(TIMER0_PRE_1024); // Prescale by 1024 // Initialize counter counter = 0; // Loop forever while(1) { timer0_set(0); // Set the timer to 0 while(timer0_read() < 156) { // Do something else for a while }; // Break out at 10 ms // Increment counter ++counter; if(counter == 50) { // When we have counted 50 of these, then toggle pin state PORTB ^= 1; counter = 0; }; }; return(0); }