微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > AVR—使用定时器必须弄清的几个概念!

AVR—使用定时器必须弄清的几个概念!

时间:11-22 来源:互联网 点击:

,请看数据手册。

定时公式:Time=PRE*(MAX-TCNT0+1) /F_cpu单位S ,其中,PRE为与分频数,本例中为8,MAX即为最大值255,TCNT0为初始化时的值,本例中为0x83(十进制的131),T_cpu,系统时钟频率,本例中为1000000。

本例程序中定时时间为:Time=8*(255-131+1)/1000000=0.001 S ,即为1ms,1Khz。可以看出,如果晶振选为8M,则定时时间变为0.000125S,也就是说晶振越大,定时时间越短,预分频越大,定时越长。

在设置时如果你选择1ms,会得到如下结果,和上面的1Khz相同。

CODE:

//TIMER0 initialize - prescale:8

// WGM: Normal

// desired value: 1mSec

// actual value: 1.000mSec (0.0%)

void timer0_init(void)

{

TCCR0 = 0x00; //stop

TCNT0 = 0x83; //set count

OCR0 = 0x7D; //set compare

TCCR0 = 0x02; //start timer

}

[Copy to clipboard]

CODE:

//ICC-AVR application builder : 2007-6-9 0:33:58

// Target : M16

// Crystal: 1.0000Mhz

// 用途:演示定时器的工作原理

// 作者:古欣

// AVR与虚拟仪器 [url]http://www.avrvi.com[/url]

#include

#include

void port_init(void)

{

PORTA = 0x00;

DDRA = 0x03; //PA0 PA1 输出

PORTB = 0x00;

DDRB = 0xFF; //PB 输出

PORTC = 0x00; //m103 output only

DDRC = 0x00;

PORTD = 0x00;

DDRD = 0x00;

}

//TIMER0 initialize - prescale:8

// WGM: Normal

// desired value: 1KHz

// actual value: 1.000KHz (0.0%)

void timer0_init(void)

{

TCCR0 = 0x00; //stop

TCNT0 = 0x83; //set count

OCR0 = 0x7D; //set compare

TCCR0 = 0x02; //start timer

}

//比较匹配中断

#pragma interrupt_handler timer0_comp_isr:20

void timer0_comp_isr(void)

{

//compare occured TCNT0=OCR0

if(OCR0==0x7D) //调整0x7D

{

OCR0=0x7F;

}

else

{

OCR0=0x7D;

}

PORTA ^= 0x01; //PA0取反

}

//溢出中断中断

#pragma interrupt_handler timer0_ovf_isr:10

void timer0_ovf_isr(void)

{

TCNT0 = 0x83; //reload counter value

PORTA ^= 0x01; //PA0取反

}

//call this routine to initialize all peripherals

void init_devices(void)

{

//stop errant interrupts until set up

CLI(); //disable all interrupts

port_init();

timer0_init();

MCUCR = 0x00;

GICR = 0x00;

TIMSK = 0x03; //timer interrupt sources 允许定时器零匹配和溢出中断

SEI(); //re-enable interrupts

//all peripherals are now initialized

}

void main(void)

{

init_devices();

PORTA=0x00;

while(1)

{

PORTB = TCNT0; //任何时候都可以读TCNT0

}

}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top