Timer 0 is very common to most of microcontroller. In this example, I use timer 0 to count the duration of any pressed button. When it is pressed (shot to ground) the program sub routine start counting the duration. If the duration exceeds 3 second, it will activate a corresponding LED. Otherwise it is exempt.
Timing diagram. When any pin become low, timer 0 start counting duration until 3 seconds to activate the corresponding output. |
Schematic diagram. SW2 used for toggling D1. SW3 used for toggling D2. Both buttons implement a pressing duration counting with timer 0. |
The MCU clock is 4 MHz. So the MCU clock period is 1/(4000000) = 250 nano seconds. I set the prescaler to 1:1024 giving the timer 0 period of 1024 x 250 nano seconds = 256 micro seconds.
I want to create 10 milli tick. So 10 milli seconds / 256 micro seconds = 39 counts.
The preload value of TCNT0 is 256 - 39 = 217 or -39 .
In the program, when the TOV0 is set to '1' we preload the TCNT0 to -39 or 217.
Simulation screen shot. D1 is toggled high after SW2 had been press for more than 3 seconds. |
No comments:
Post a Comment