728x90

728x90

Saturday, May 23, 2020

Using timer 0 of ATMega32 to make a retentive timer low

In an MCU application, when you pressed a button accidentally or by mistake, the related process will activated. To prevent this, we could use a timer to count the duration of the button that being pressed.

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. 


Using timer 0 of ATMega32 to detect long pressed buttons
Timing diagram.
When any pin become low, timer 0 start counting
duration until 3 seconds to activate the corresponding
output.

Using timer 0 of ATMega32 to detect long pressed buttons
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.


C source code; 


#include <avr/io.h>

unsigned int tenMillis=0;
unsigned int tenMilliSecond(void){
//Check if TIFR is set
if(TIFR&0x01){
//Preload TCNT0
TCNT0=-39;
//Clear flag
TIFR=0x01;
tenMillis+=1;
}
return tenMillis;
}

int main(void)
{
    //Set PortC to Output
DDRC=0xC0;
//Clear PortC
PORTC=0x03;
//Set 1:1024 prescaler
TCCR0=0x05;
//Clear overflow flag
TIFR=0x01;
    while (1) 
    {
while((PINC&0x01)==0){
if (tenMilliSecond()>300)
{
PORTC^=0x80;
break;
}
}
tenMillis=0;
while((PINC&0x02)==0){
if (tenMilliSecond()>300)
{
PORTC^=0x40;
break;
}
}
tenMillis=0;
    }
}

A screen shot of this example:

Using timer 0 of ATMega32 to detect long pressed buttons
Simulation screen shot.
D1 is toggled high after SW2 had been press
for more than 3 seconds.
Back to main tutorial page ATMega32 tutorials in C with Atmel Studio 7.







No comments:

Post a Comment

320x50

Search This Blog

tyro-728x90