atmega16单片机定时器t2实现1s定时
2个回答
展开全部
//ICC-AVR application builder : 2016-1-4 上午 11:32:30
// Target : M16
// Crystal: 12.000Mhz
#include <iom16v.h>
#include <macros.h>
//利用T2实现2ms定时,而后计时500次就是1S
unsigned int dly_ms,timer_1s;
void port_init(void)
{
PORTA = 0x00;
DDRA = 0x00;
PORTB = 0x00;
DDRB = 0x00;
PORTC = 0x00; //m103 output only
DDRC = 0x00;
PORTD = 0x00;
DDRD = 0x00;
}
//TIMER2 initialize - prescale:128
// WGM: Normal
// desired value: 2mSec
// actual value: 1.995mSec (0.3%)
void timer2_init(void)
{
TCCR2 = 0x00; //stop
ASSR = 0x00; //set async mode
TCNT2 = 0x45; //setup
OCR2 = 0xBB;
TCCR2 = 0x05; //start
}
#pragma interrupt_handler timer2_ovf_isr:5
void timer2_ovf_isr(void)
{
TCNT2 = 0x45; //reload counter value
dly_ms++;//2MS定时
if(dly_ms>=500) //定时2ms*500=1000ms=1S
{
dly_ms=0; //500次复位后继续冲0-500
timer_1s++; //1S往上加吧!!!!
}
}
//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
CLI(); //disable all interrupts
port_init();
timer2_init();
MCUCR = 0x00;
GICR = 0x00;
TIMSK = 0x40; //timer interrupt sources
SEI(); //re-enable interrupts
//all peripherals are now initialized
}
main()
{
init_devices();//设备初始化
while(1)//作死的循环吧
;
}
// Target : M16
// Crystal: 12.000Mhz
#include <iom16v.h>
#include <macros.h>
//利用T2实现2ms定时,而后计时500次就是1S
unsigned int dly_ms,timer_1s;
void port_init(void)
{
PORTA = 0x00;
DDRA = 0x00;
PORTB = 0x00;
DDRB = 0x00;
PORTC = 0x00; //m103 output only
DDRC = 0x00;
PORTD = 0x00;
DDRD = 0x00;
}
//TIMER2 initialize - prescale:128
// WGM: Normal
// desired value: 2mSec
// actual value: 1.995mSec (0.3%)
void timer2_init(void)
{
TCCR2 = 0x00; //stop
ASSR = 0x00; //set async mode
TCNT2 = 0x45; //setup
OCR2 = 0xBB;
TCCR2 = 0x05; //start
}
#pragma interrupt_handler timer2_ovf_isr:5
void timer2_ovf_isr(void)
{
TCNT2 = 0x45; //reload counter value
dly_ms++;//2MS定时
if(dly_ms>=500) //定时2ms*500=1000ms=1S
{
dly_ms=0; //500次复位后继续冲0-500
timer_1s++; //1S往上加吧!!!!
}
}
//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
CLI(); //disable all interrupts
port_init();
timer2_init();
MCUCR = 0x00;
GICR = 0x00;
TIMSK = 0x40; //timer interrupt sources
SEI(); //re-enable interrupts
//all peripherals are now initialized
}
main()
{
init_devices();//设备初始化
while(1)//作死的循环吧
;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询