| 
 
| #include <reg51.h> #define uInt unsigned int
 #define uchar unsigned char
 uchar PWM_T1 = 0;   //占空比控制变量
 uchar PWM_T2 = 0;
 sbit c7=P3^7;  //6个按键,决定输出PWM_T值
 sbit c6=P3^6;
 sbit c5=P3^5;
 sbit c4=P3^4;
 sbit c3=P3^3;
 sbit c2=P3^2;
 sbit OUT1=P1^0;
 sbit OUT2=P1^1;
 void main(void)
 {
 uInt n;
 TMOD=0x02;   //定时器0,工作模式2,8位定时模式
 TH0=210;     //写入预置初值(取值1-255,数越大PWM频率越高)
 TL0=210;     //写入预置值 (取值1-255,数越大PWM频率越高)
 TR0=1;       //启动定时器
 ET0=1;       //允许定时器0中断
 EA=1;        //允许总中断
 OUT1=0xff;     //初始化P1
 OUT2=0xff;
 
 while(1)      //PWM周期100,高电平100- PWM_T, 低电平PWM_T,低电平工作
 {
 for(n=0;n<200;n++);           //延时,取值0-65535,数字越大变化越慢
 if(!c7||!c6||!c5||!c4||!c3||!c2)     //通过按键改变占空比
 {
 if(!c7)         {PWM_T1=0;    PWM_T2=100;         }
 else if(!c6)   { PWM_T1=10;           PWM_T2=85;  }
 else if(!c5)   { PWM_T1=35;           PWM_T2=60;          }
 else if(!c4)   { PWM_T1=60;           PWM_T2=35;         }
 else if(!c3)   { PWM_T1=85;           PWM_T2=10;  }
 else if(!c2)   { PWM_T1=100;   PWM_T2=0;         }
 }
 }
 }
 timer0() interrupt 1
 {
 static  uchar   t1 ;   //PWM计数
 t1++;    //每次定时器溢出加1
 
 if(t1==100)   //PWM周期 100个单位
 {
 t1=0;  //使t=0,开始新的PWM周期
 OUT1=0x00;                 //使LED灯亮  ,输出端口
 
 }
 
 if(PWM_T1==t1)  //按照当前占空比切换输出为高电平
 {    OUT1=0xff;   //使LED灯灭
 
 }
 }
 
 timer1() interrupt 1
 {
 static  uchar   t2 ;   //PWM计数
 t2++;    //每次定时器溢出加1
 
 if(t2==100)   //PWM周期 100个单位
 {
 t2=0;  //使t=0,开始新的PWM周期
 OUT2=0x00;
 }
 
 if(PWM_T2==t2)  //按照当前占空比切换输出为高电平
 {   OUT2=0xff;   //使LED灯灭
 }
 }
 只有OUT2可以输出信号
 | 
 |