//LED灯由亮到灭,由灭到亮逐步变化
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit LED = P1^2;
uchar CYCLE; //定义周期 该数字X基准定时时间 如果是10 则周期是10 x 0.1ms
uchar PWM_ON ;//定义高电平时间
void delay(uint cnt)
{
while(--cnt);
}
void main()
{
bit Flag;
TMOD |=0x01;//定时器设置 0.1ms in 12M crystal
TH0=(65536-100)/256;
TL0=(65536-100)%256;//定时0.1mS
IE= 0x82; //打开中断
TR0=1;
CYCLE = 10;// 时间可以调整 这个是10调整 8位PWM就是256步
while(!Flag)
{
delay(200000000); //延时时间,从一个亮度到下一个亮度的间隔时间,速度快就能看到连续效果
PWM_ON++; //这个使用较长延时,以便能看清楚变化过程
if(PWM_ON == CYCLE)
{ //这个里可以添加其他程序 如到最亮时候控制设备
Flag=1;
}
}
while(Flag) //亮度递减 同上,是个相反的过程
{
delay(200000000);
PWM_ON--;
if(PWM_ON == 0)
{
Flag=0;
}
}
}
void Timer0(void) interrupt 1 using 1
{
static uchar count; //
TH0=(65536-100)/256;
TL0=(65536-100)%256;//定时0.1mS
if (count==PWM_ON)
{
LED = 1; //灯灭
}
count++;
if(count == CYCLE)
{
count=0;
if(PWM_ON!=0) //如果左右时间是0 保持原来状态
LED = 0;//灯亮
}
}