#include<reg52.h> //Include the header file. Generally, no modification is required. The header file contains the definition of special function registers.
sbit LED1 = P2^0;
sbit LED = P2^1; //Define LED light and display dimming effect through LED
sbit LED2 = P2^2;
unsigned char CYCLE; //define the cycle. If the digital X reference timing time is 10, the cycle is 10 x 0.1ms
unsigned char PWM_ON ;//define the high level time
/******************************************************************/
/* Delay function &nbs/******************************************************************/
void delay(unsigned int cnt)
{
while(--cnt);
}
/**********************************************************************/
/* Main function */
/**********************************************************************/
void main()
{
bit Flag;
TMOD |=0x01; //timer setting 0.1ms in 12M crystal
TH0=(65536-100)/256;
TL0=(65536-100)%256; //timing 0.1mS
IE= 0x82; //Turn on interrupt
TR0=1;
CYCLE = 50; //The time can be adjusted to 10. Adjusting 8-bit PWM means 256 steps
while(!Flag)
{
delay(20000); //Delay time, the interval from one brightness to the next brightness. If the speed is fast, you can see the continuous effect
PWM_ON++; //This uses a longer delay so that you can see the change process clearly
if(PWM_ON == CYCLE)
{ //You can add other programs here, such as controlling the device when it is brightest
Flag=1;
}
}
while(Flag) //Brightness decreases as above, which is an opposite process
{
delay(20000); //The delay time is 20000*0.4=8000us
PWM_ON--;
if(PWM_ON == 0)
{
Flag=0;
}
}
}
/**************************************************************************/
/* Timer interrupt function */
/**************************************************************************/
void tim(void) interrupt 1 using 1
{
static unsigned char count;
TH0=(65536-100)/256;
TL0=(65536-100)%256; //timing 0.1mS
if (count==PWM_ON)
{
LED1 = 1;
LED = 1; //light off
LED2 = 1;
}
count++;
if(count == CYCLE)
{
count=0;
if(PWM_ON!=0) //if the on time is 0, keep the original state
{
LED1 = 0;
LED = 0; //light on
LED2 = 0;
}
}
}
|