Atmega2560 Basic Course (5) - 8-bit timer (TIM0 / 2) timer interrupt
Atmega2560 a total of two 8-bit timers, timer 0, timer 2, so that a simple 8-bit timers in the timer interrupt requires three registers, TCNTx, TCCRxB, TIMSKx (x = 0,2), the timer 0 and 2 are basically the same structure, the following are an example timer 0
1. Works
TCNTx value of the timer increments up in value that is added to TOP 0XFF, interrupt flag. DETAILED TCNTx value is calculated as follows:
Time units of the formula s, frequency hz, without conversion unit
2.TCNTx register
Starting 8-bit register, count
3.TCCRxB register
The main decision to divide the number of
DETAILED arranged as follows:
4.TIMSKx register
The main Enable interrupt
5. Specific examples of
Timer to 0, for example, you need a friend timer 2 can be replaced which register to use timer 2
/*
定时器0,256分频,当中断发生时,PA0电平翻转
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/sfr_defs.h>
#include <avr/interrupt.h>
#include <math.h>
float a=0.002; //0.002s产生一次中断
int i=0;
int main(void)
{
a=256-(F_CPU/256*a); //计算初值
i=a; //取整
cli();
DDRA|=_BV(DDA0);
PORTA|=_BV(PA0);
TCNT0=i;
TCCR0B |=_BV(CS02); //设定256分频
TIMSK0 |=_BV(TOIE0); //使能溢出中断
sei();
while (1)
{
}
}
ISR(TIMER0_OVF_vect){
cli();
TCNT0=i;
PORTA^=(1<<PA0);
sei();
}
Waveform chart