This article introduces a program of 51 series single-chip microcomputer that uses pulse width modulation (PWM) to control the brightness of LED lights. We all know that 51 Single-Chip Microcomputer itself has no pwm interface. This program is
The software simulates pwm and adjusts the duty cycle of high voltage and low level in a certain frequency square wave to realize the brightness control of the LED lamp. In the program, the timer 0 is used to generate a Ms Cycle Pulse,
Use the duty cycle control variable scale to control the duty cycle, enable the LED light to light up during the low level, disable the LED light during the High Level, change the scale to change the time of the high level and the low level, so
This controls the brightness of the LED lamp.
# Include "AT89X51. H" // simulate 10 brightness levels of the PWM output control Lamp
Unsigned int scale; // duty cycle control variable
Void main (void) // main program
{
Unsigned int n; // The variable of the delayed loop.
TMOD = 0x02; // timer 0, Working Mode 2 (), 8-bit scheduled Mode
TH0 = 0x06; // write the preset Initial Value 6 to the timer 0, so that 250 microseconds overflow once (12 MHz)
TL0 = 0x06; // write preset values
TR0 = 1; // start the timer
ET0 = 1; // allows the timer to interrupt 0
EA = 1; // allow total interruptions
While (1) // infinite loop. in actual application, this is the main task.
{
For (n = 0; n <50000; n ++); // the brightness of a class is automatically added every time.
Scale ++; // The duty cycle control variable scale plus 1
If (scale = 10) scale = 0; // if scale = 10, set scale to 0
}
}
Void timer0 (void) interrupt 1 // timer 0 interrupt the Service Program
{
Static unsigned int tt; // tt is used to save the proportional position of the current time in one second.
Tt ++; // increase by 1 every 250 microseconds
If (tt = 10) // 2.5 millisecond clock cycle
{
Tt = 0; // enable tt = 0 to start a new PWM cycle
P2_0 = 0; // enable LED light
}
If (scale = tt) // switch the output to a high level based on the current duty cycle
P2_0 = 1; // turn off the LED light
}
In the program, from tt = 0 to scale is low, and from scale to tt = 10 is high. Because scale is a variable, changing scale can change the duty cycle.