oc2输出pwm._c

来自「ICC mega8例子」· _C 代码 · 共 65 行

_C
65
字号
//ICC-AVR application builder : 2009-3-11 13:30:36
// Target : M8
// Crystal: 8.0000Mhz

#include <iom8v.h>
#include <macros.h>

void port_init(void)
{
 PORTB = 0x00;
 DDRB  = 0x00;
 PORTC = 0x00; //m103 output only
 DDRC  = 0x00;
 PORTD = 0x00;
 DDRD  = 0x00;
}

//call this routine to initialize all peripherals
void init_devices(void)
{
 //stop errant interrupts until set up
 CLI(); //disable all interrupts
 port_init();

 MCUCR = 0x00;
 GICR  = 0x00;
 TIMSK = 0x00; //timer interrupt sources
 SEI(); //re-enable interrupts
 //all peripherals are now initialized
}

/************************************
用    途:用TC2的PWM进行相位可调输出
Taget   :mega8
crystal :8M
介    绍:输出为OC2(PB3)
入口参数:n为0-255,代表占空比
出口参数:
*************************************/
void init_timer2_PWM(unsigned char n)
{
 DDRB=(1<<PB3);
 TCCR2=0;//TC2处于定时方式,先停止TC2
 TCNT2=0;//设初值
 OCR2=255-n;//设比较参考值//恒定低电平
 TIMSK&=(~((1<<OCIE2)|(1<<TOIE2)));//关闭TOV2中断
 //打开TC2选择相位可调PWM模式,64分频
 TCCR2|=(1<<WGM20)|(1<<COM21)|(1<<COM20)|(1<<CS22);
}
void timer2_PWM(unsigned char n)
{
 OCR2=255-n;
}

void main()
{
 port_init();
 init_devices();
 
 init_timer2_PWM(100);
 while(1)
 {
  ;
 }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?