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

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

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

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