Answer:
Programming steps :
1. Intialize TNCNT0 to value 0.
2. Program prescalar by setting CS bits of TCCR0.
3. Set Timer Overflow Interrupt TOIE0 bit of TIMSK register.
4. Enable global interrupt by sei() command.
5. write code for ISR function with vector name TIMER_OVF_vect.
ATmega168/328 Code:
CODE 1:
// this code sets up a timer0 for 1ms @ 16Mhz clock cycle
// in order to function as a time delay at the beginning of the
main loop
// using no interrupts
#include <avr/io.h>
int main(void)
{
while (1)
{
// Set the Timer Mode to
CTC
TCCR0A |= (1 <<
WGM01);
// Set the value that
you want to count to
OCR0A = 0xF9;
// start the timer
TCCR0B |= (1 << CS01) | (1
<< CS00);
// set prescaler to 64 and start
the timer
while ( (TIFR0 &
(1 << TOV0) ) > 0) // wait for the
overflow event
{
}
TIFR0 |= (1 <<
TOV0);
// reset the overflow
flag
}
}
CODE 2:
// this code sets up a timer0 for 4ms @ 16Mhz clock cycle
// an interrupt is triggered each time the interval occurs.
#include <avr/io.h>
#include <avr/interrupt.h>
int main(void)
{
// Set the Timer Mode to
CTC
TCCR0A |= (1 <<
WGM01);
// Set the value that
you want to count to
OCR0A = 0xF9;
TIMSK0 |= (1 <<
OCIE0A); //Set the ISR COMPA vect
sei(); //enable interrupts
TCCR0B |= (1 <<
CS02);
// set prescaler to 256 and start
the timer
while (1)
{
// main loop
}
}
ISR (TIMER0_COMPA_vect) // timer0 overflow interrupt
{
// event to be executed every 4ms here
}
I am using the ATmega328P only. please do NOT use any other microprocessor. 2. Timer0 is...