ATmega16 定时计数器器应用

这里使用ATmega16完成溢出中断功能

1、初始化定时器参数

// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
// Mode: Normal top=0xFF
// OC0 output: Disconnected
TCCR0=(0<<WGM00) | (0<<COM01) | (0<<COM00) | (0<<WGM01) | (0<<CS02) | (1<<CS01) | (0<<CS00); //设置分频
TCNT0=0x37; //设置初值 
OCR0=0x00;

预设频率16MHz,这里选择010,8分之一分频,2MHz,时钟周期0.5us,产生一个100us的时钟周期需要200个周期,所以时间t=(255-55)*0.5,所以初值TCNT0=0x37; //设置初值

2、设置时钟使能

// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=(0<<OCIE2) | (0<<TOIE2) | (0<<TICIE1) | (0<<OCIE1A) | (0<<OCIE1B) | (0<<TOIE1) | (0<<OCIE0) | (1<<TOIE0);
3、打开全局使能

// Global enable interrupts
#asm("sei")

4、写入中断程序

// Declare your global variables here
volatile unsigned int cnt=0;
// Timer 0 overflow interrupt service routine
interrupt [TIM0_OVF] void timer0_ovf_isr(void)
{
// Place your code here
     TCNT0=0x37;   //重新赋予初值
     cnt++;                 //计数
  if(cnt>=1000)  
  {
      cnt=0;                //重新开始计数
      PORTB^=0xff;   //灯闪烁
  }

}
 

发布了14 篇原创文章 · 获赞 3 · 访问量 3407

猜你喜欢

转载自blog.csdn.net/eben_8292/article/details/105052758