用TIME0产生0.5s的中断。
首先预分频1024
14.7456M/1024=14.444KHz
一个脉冲的周期为1/14.4444k=69.44us
既是每隔69.44us 计数器加1计数。
定时器0为8位的,可以计数256个 则最大计数为256*69.44us=17.7777ms
我们要500ms 则要开发全局计数器
我们用10ms产生中断,全局计数器要500/10=50次后触发LED。
我们用10ms/69.44us=144(10ms的中断), 256-144=112为计数器的初值。
所以timecount=50
//ICC-AVR application builder : 2006-7-13 16:11:26
// Target : M128
// Crystal: 14.7456Mhz
#include <iom128v.h>
#include <macros.h>
unsigned int timecount=0;
void port_init(void)
{
PORTA = 0x00;
DDRA = 0x00;
PORTB = 0xFF;
DDRB = 0xFF; //B端口输出,初值为FF
PORTC = 0x00; //m103 output only
DDRC = 0x00;
PORTD = 0x00;
DDRD = 0x00;
PORTE = 0x00;
DDRE = 0x00;
PORTF = 0x00;
DDRF = 0x00;
PORTG = 0x00;
DDRG = 0x00;
}
//TIMER0 initialize - prescale:1024
// WGM: Normal
// desired value: 14.44444444KHz
// actual value: -0.001KHz (1444544.4%)
void timer0_init(void)
{
TCCR0 = 0x00; //stop
ASSR = 0x00; //set async mode
TCNT0 = 0x00; //set count
OCR0 = 0x00;
TCCR0 = 0x07; //start timer 预分频为1024
}
#pragma interrupt_handler timer0_ovf_isr:17
void timer0_ovf_isr(void)
{
TCNT0 =112; //reload counter value置计数初值112
if (++timecount==50)//软件计数器为50
{
PORTB=PORTB^0xc3; //取反
timecount=0;
}
}
//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
CLI(); //disable all interrupts
XDIV = 0x00; //xtal divider
XMCRA = 0x00; //external memory
port_init();
timer0_init();
MCUCR = 0x00;
EICRA = 0x00; //extended ext ints
EICRB = 0x00; //extended ext ints
EIMSK = 0x00;
TIMSK = 0x00; //timer interrupt sources
ETIMSK = 0x00; //extended timer interrupt sources
SEI(); //re-enable interrupts
//all peripherals are now initialized
}
void main(void)
{
port_init();
timer0_init();
init_devices();
TIMSK=0x01;
#asm("sei")
while(1)
{
;
}
}