Using the TMR0 interrupt to create a real time clockYou should now have an AVR set up on a breadboard. In this section I will lead you through the steps to create a real time clock on the AVR, accurate to a few parts per thousand. This accuracy is needed in many real-time control and interface applications. |
|
|

Figure 1 Program flow without, and with, an interrupt
|
The AVR has 16 different "interrupt sources", meaning that you can write 16 interrupt handlers which can react to 16 different messages. Some are "external" events, for example a voltage change on a special pin. Some are "internal" messages such as "a timer has overflowed" (this is explained below). Understanding how to use the various interrupts is the key to achieving a good design. |
|
|
|
|
|
|
|
|
|
// enable timer 0 overflow interrupt TIMSK |= BIT(TOIE0); |
There is also a single "master switch" which controls whether ALL interrupts will be enabled or disabled. It is called the "Global Interrupt Enable" flag and it can be controlled using these commands:
// enable all interrupts SEI();
// disable all interrupts CLI();
|
The timer we wish to use, Timer 0, also has some additional controls. By putting values into them we can control the timer period very accurately.
TCCR0 controls a pre-scaler. This is a system that divides the main oscillator frequency by a power of 2. The main oscillator runs at 8MHz (typically) and this is very fast. If we want a long delay between overflow interrupts, we need to use a slower clock using the prescaler.
TCNT0 is the actual count value. We can read this at any time, and we can also write data to it. See the definition of overflow to understand why this is useful.
Same hardware setup as for hello.c, only one LED needed on pin 0 of PORTC.

Figure 2 Example program that uses the TMR0 interrupt
|
So what?The previous program, hello.c, had a flashing light but the timing was not precise. The problem was that the delay came from wasted CPU cycles in the main program. In that program, if an interrupt happened, it would cause a delay to the LED period. Not so good. This program has a more accurate form of timing which will remain steady whether there are other interrupts or not (with a few caveats, as usual). So if you need precise timing, it's a good idea to set up TMR0 or one of the other timers to keep time for you.ExercisesPlay with this code until you understand it. Suggestions:
|