|
AVR单片机TO定时器快速PWM模式范例:
/*///////////////////////////////////////////////
///////定时器TO的使用例程——快速PWM模式/////////
//作者:宝山
//时间:2008.06.02
//编译环境:ICCV7 for AVR
//晶体: 11.0592Mhz
///////////////////////////////////////////////*/
#include
#include
void port_init(void)
{
PORTA = 0x00;
DDRA = 0x00;
PORTB = 0x00;
DDRB = 0x08; //PB3为PWM输出
PORTC = 0x00; //m103 output only
DDRC = 0x00;
PORTD = 0x00;
DDRD = 0x00;
}
void timer0_init(void)
{
TCCR0 = 0x00; //stop
TCNT0 = 0x01;
OCR0 = 0xF0; //改变此值可改变占空比
TCCR0 = 0x7D; //设置为快速PWM模式,匹配时OC0置1,分频系数1024
}
// 频率计算公式:fOCn= fclk/(N*256)
// N=1024
// fOC0=11059200/(1024*256)=42.1875Hz
// 在PB3管脚输出占空比可调,频率为42.1875Hz的PWM信号
// 通过改变分频系数N改变频率
#pragma interrupt_handler timer0_comp_isr:iv_TIM0_COMP
void timer0_comp_isr(void)
{
//compare occured TCNT0=OCR0
}
#pragma interrupt_handler timer0_ovf_isr:iv_TIM0_OVF
void timer0_ovf_isr(void)
{
TCNT0 = 0x01; //reload counter value
}
void init_devices(void)
{
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();
while(1);
}
|
|