电流、负载不变的情况下,调整电压,实际上电流也在不断的变化;也可以通过输出脉冲信号,调整占空比来控制亮度。
#include <REG52.H> #define LED P1 #define LED_ON() LED=0x00; #define LED_OFF() LED=0xFF; #define LED_PWM_LIMIT_MAX 99 #define LED_PWM_LIMIT_MIN 0 static unsigned int s_u8TimeCounter = 0 ; //中断计数 static unsigned int s_u8LedDirection = 0 ; //LED方向控制 0 :渐亮 1 :渐灭 static int s_s8LedPWMCounter = 0 ; //LED占空比 void Timer0Init(void){ TMOD &=0xF0; TMOD |=0x01; TH0=0xFF; TL0=0x47; TR0=1; ET0=1; } void Time0Isr(void) interrupt 1 { static int s_s8PWMCounter = 0 ; TH0=0xFF; //定时器重新赋初值 TL0=0x47 ; if(++s_u8TimeCounter >= 100) //每20MS调整一下LED的占空比 { s_u8TimeCounter = 0 ; //如果是渐亮方向变化,则占空比递增 if((s_s8LedPWMCounter <= LED_PWM_LIMIT_MAX) &&(0 ==s_u8LedDirection)) { s_s8LedPWMCounter++ ; if(s_s8LedPWMCounter > LED_PWM_LIMIT_MAX) { s_u8LedDirection = 1 ; s_s8LedPWMCounter = LED_PWM_LIMIT_MAX ; } } //如果是渐暗方向变化,则占空比递渐 if((s_s8LedPWMCounter >= LED_PWM_LIMIT_MIN) &&(1 ==s_u8LedDirection)) { s_s8LedPWMCounter-- ; if(s_s8LedPWMCounter < LED_PWM_LIMIT_MIN) { s_u8LedDirection = 0 ; s_s8LedPWMCounter = LED_PWM_LIMIT_MIN ; } } s_s8PWMCounter = s_s8LedPWMCounter ; //获取LED的占空比 } if(s_s8PWMCounter > 0) //占空比大于0,则点亮LED,否则熄灭LED { LED_ON() ; s_s8PWMCounter-- ; } else { LED_OFF(); } } void main(void){ Timer0Init(); EA=1; while(1); }