《STC单片机PWM的实现.docx》由会员分享,可在线阅读,更多相关《STC单片机PWM的实现.docx(3页珍藏版)》请在三一办公上搜索。
1、STC单片机PWM的实现08 2月 STC单片机PWM的实现 PWM波是数字向模拟转换的一种重要方法,通常使用单片机的定时器做频率发生器,含有数字比较器,当设定值与定时器的值相等,引脚的电平发生翻转。控制设定值,就控制了PWM波占空比,通过滤波,输出直流模拟量。 #include sfr CCON =0xD8; sfr CMOD =0xD9; sfr CCAPM0 =0xDA; sfr CCAPM1 =0xDB; sfr CCAPM2 =0xDc; sfr CCAPM3 =0xDd; sfr CL =0xE9; sfr CH =0xF9; sfr CCAP0L =0xEA; sfr CCAP0
2、H =0xFA; sfr CCAP1L =0xEb; sfr CCAP1H =0xFb; sfr CCAP2L =0xEc; sfr CCAP2H =0xFc; sfr CCAP3L =0xEd; sfr CCAP3H =0xFd; sbit CR =0xDE; void init_pwm /定时器的来源CPS1,CPS0 CMOD=0x02;/Setup PCA timer CL=0x00; CH=0x00; /控制占空比 void pulse_0(unsigned char p_on) CCAP0L=p_on;/Set the initial value same as CCAP0H CC
3、AP0H=p_on;/ /CCAPMn.1使能脉宽调制模式,EC0M必须=1 CCAPM0=0x42;/0100,0010 Setup PCA module 0 in PWM mode void pulse_1(unsigned char p_on) CCAP1L=p_on;/Set the initial value same as CCAP0H CCAP1H=p_on;/25% Duty Cycle /CCAPMn.1使能脉宽调制模式,EC0M必须=1 CCAPM1=0x42;/0100,0010 Setup PCA module 0 in PWM mode void pulse_2(un
4、signed char p_on) CCAP2L=p_on;/Set the initial value same as CCAP0H CCAP2H=p_on;/25% Duty Cycle /CCAPMn.1使能脉宽调制模式,EC0M必须=1 CCAPM2=0x42;/0100,0010 Setup PCA module 0 in PWM mode void pulse_3(unsigned char p_on) CCAP3L=p_on;/Set the initial value same as CCAP0H CCAP3H=p_on;/25% Duty Cycle /CCAPMn.1使能脉
5、宽调制模式,EC0M必须=1 CCAPM3=0x42;/0100,0010 Setup PCA module 0 in PWM mode void delay(int a) int i; for(i=0;ia;i+); void main(void) unsigned char i=0; init_pwm; CR=1; /Start PCA Timer while(1) while(+i) pulse_0(i+50); pulse_1(i+100); pulse_2(i+150); pulse_3(i+200); delay(1000); while(-i) pulse_0(i+50); pulse_1(i+100); pulse_2(i+150); pulse_3(i+200); delay(1000);