例如:定时200ms ,晶振8MHZ,分频系数1024,计数时钟频率为8MHZ/1024=8000000HZ/1024=7812.5HZ,每个计数脉冲的周期时间为1/7812.5=0.128ms,计时200ms的计数器值为:65635-200ms/0.128ms=63972=0xF9E4 ,则TCNT1H付初值为0xF9,TCNT1L付初值为0xE4.
//函数功能:实现PA口的led亮0.1S,灭0.9S
#include <iom16.h>
#define uchar unsigned char
/********以下是端口初始化函数********/
void port_init()
{
DDRA = 0xFF; //PA设置为输出口
PORTA = 0xFF; //PA输出高电平
}
/********定时器1初始化********/
void timer1_init()
{
TCNT1H = 0xCF;//计数器置初值
TCNT1L = 0x2C;
TCCR1A |= 0x00; //普通端口模式
TCCR1B |= (1<<CS11)|(1<<CS10); //64分频
TIMSK&=(1<<TOIE1); //使能T1溢出中断
}
/********以下是主函数********/
void main(void)
{
uchar count,T1_OVR;
port_init();
timer1_init();
while(1)
}
/*定时器1中断函数*/
#pragma interrupt_handler timer1_ovf:9
void timer1_ovf(void)
{
TCNT1H=0xCF;
TCNT1L=0x2C;
COUNT++
if (count==9)
PORTA=0x00;
if (count>=10
{
count=0;
PROTA=0xFF;
}