一、概述
使用51单片机控制LED,实现其由暗变亮,再由亮变暗的渐变过程。
二、程序
#include <STC15F2K60S2.H>
#include "MacroAndConst.h"
sbit LED = P1^5;
#define LED_ON() LED = 0; //LED亮
#define LED_OFF() LED = 1; //LED灭
#define LED_PWM_LIMIT_MAX 99
#define LED_PWM_LIMIT_MIN 0
static u8 s_u8TimeCounter = 0; //中断计数
static u8 s_u8LedDirection = 0; //LED方向控制 0:渐亮 1:渐灭
static u8 s_u8LedPWMCounter = 0; //LED占空比
void Timer0Init(void)
{
AUXR |= 0x80; //定时器时钟1T模式
TMOD &= 0xF0; //设置定时器模式
TL0 = 0x5C; //设置定时初值
TH0 = 0xF7; //设置定时初值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0 = 1; //使能定时器0中断
}
void Timer0Isr(void) interrupt 1
{
static int8 s_u8PWMCounter = 0;
TH0 = 0xF7; //定时器初始值(200us中断1次)
TL0 = 0x5C;
if(++s_u8TimeCounter >= 100) //每20ms调整一次LED占空比
{
s_u8TimeCounter = 0;
//如果是渐亮方向变化,则占空比递增
if((s_u8LedPWMCounter <= LED_PWM_LIMIT_MAX)&&(s_u8LedDirection == 0))
{
s_u8LedPWMCounter++;
if(s_u8LedPWMCounter > LED_PWM_LIMIT_MAX)
{
s_u8LedDirection = 1;
s_u8LedPWMCounter = LED_PWM_LIMIT_MAX;
}
}
//如果是渐灭方向变化,则占空比递减
if((s_u8LedPWMCounter > LED_PWM_LIMIT_MIN)&&(s_u8LedDirection == 1))
//此处有坑,若写成“>=”,则达不到预期效果
{
s_u8LedPWMCounter--;
if(s_u8LedPWMCounter <= LED_PWM_LIMIT_MIN)
{
s_u8LedDirection = 0;
s_u8LedPWMCounter = LED_PWM_LIMIT_MIN;
}
}
s_u8PWMCounter = s_u8LedPWMCounter; //获取LED的占空比
}
if(s_u8PWMCounter > 0) //占空比大于0,则点亮LED,否则熄灭
{
LED_ON();
s_u8PWMCounter--;
}
else
{
LED_OFF();
}
}