STC15W408AS内置硬件PWM,正常运行不占用CPU资源,控制CCAP0H寄存器预装值0x00~0xff就能控制占空比。呼吸灯示例程序
- #include <STC15F2K60S2.H>
- #define uint unsigned int
- #define uchar unsigned char
- //sbit key1=P4^2;
- //sbit key2=P4^4;
- //sbit LED=P1^0;
- uchar num=0x00; //占空比变量
- bit a=0; //呼吸位变量
- uint b; //延时计数变量
- void PWM_Init()
- {
- CCON = 0; //初始化PCA控制寄存器
- //PCA定时器停止
- //清除CF标志
- //清除模块中断标志
- CL = 0; //复位PCA寄存器
- CH = 0;
- CMOD = 0x02; //设置PCA时钟源,PWM频率=12MHZ/2/256=23.4375KHZ
- //PWM频率=11.0592MHZ/2/256=21.600KHZ
- PCA_PWM0 = 0x00; //PCA模块0工作于8位PWM
- CCAP0H = CCAP0L = 0xff; //PWM0的占空比为0%(0x00=100%)
- CCAPM0 = 0x42; //PCA模块0为8位PWM模式
- CR = 1; //PCA定时器开始工作
- }
- void scan()
- {
- static uint count1=0,count2=0;
- if(a==0)
- {
- count1++;
- if(count1>=2000)
- {
- count1=0;
- if(num<0xff)
- {
- num++;
- if(num==0xff)
- {
- a=1;
- b=5000;
- while(b--);
- }
- }
- }
- }
- else
- {
- count2++;
- if(count2>=2000)
- {
- count2=0;
- if(num>0)
- {
- num--;
- if(num==0)
- {
- a=0;
- b=5000;
- while(b--);
- }
- }
- }
- }
- }
- void main()
- {
- P1M0 = 0x01; //P1.0端口推挽输出模式
- P1M1 = 0x00;
- PWM_Init(); //初始化PWM
- while(1)
- {
- scan(); //呼吸扫描
- CCAP0H=num; //P1.0输出PWM
- }
- }
复制代码
|