3C Computer,Industrial Electronics,Electrical Relay Blog - slnselectronics.com

September 29, 2025

PWM control LED lamp brightness program (C language)

Controlling the brightness of an LED can be done by adjusting the voltage, but this method is not ideal due to its limited range and the risk of damaging the LED if the voltage is too high. The most effective and widely used technique for controlling LED brightness is through Pulse Width Modulation (PWM). PWM allows for precise control of the light intensity by varying the duty cycle of the signal, making it a reliable and efficient solution.

The following code demonstrates how to control an LED using PWM on a microcontroller. This example includes basic functions for adjusting the brightness and managing interrupts for timing purposes.

//**************************************

// PWM Control for LED Brightness

// Author: Yong

//**************************************

#include <reg52.h>

sbit speaker = P2^1; // Define speaker control pin

sbit up = P1^5; // Define UP key

sbit down = P1^6; // Define DOWN key

static unsigned char pwm;

unsigned char t;

void delay(unsigned char ms);

void beep(void);

void alarm_delay(void);

void main()

{

TMOD = 0x21; // Timer 0 in mode 1, Timer 1 in mode 2

ET0 = 1; // Enable Timer 0 interrupt

ET1 = 1; // Enable Timer 1 interrupt

EA = 1; // Enable global interrupts

TH0 = 0xFC; // Set timer 0 for 1ms

TL0 = 0x18;

TH1 = 0x9C; // Set timer 1 for 0.1ms

TL1 = 0x00;

TR0 = 1; // Start Timer 0

PT1 = 1; // Set Timer 1 as high priority

pwm = 0x9C; // Initial PWM value

while(1)

{

do

{

pwm++;

delay(10);

if(pwm == 0xFF) beep();

} while(pwm != 0xFF);

do

{

pwm--;

delay(10);

if(pwm == 0x01) beep();

} while(pwm != 0x01);

}

}

void Timer0() interrupt 1

{

TH0 = 0xFC;

TL0 = 0x18;

TR1 = 1;

TH1 = pwm;

P0 = 0x00;

}

void Timer1() interrupt 3

{

P0 = 0xFF;

TR1 = 0;

}

void delay(unsigned char ms)

{

unsigned char i = 120;

while(ms--)

{

while(i--);

}

}

void beep(void)

{

unsigned char b;

for(b=40; b>=2; b--)

{

speaker = ~speaker;

alarm_delay();

}

speaker = 1;

}

void alarm_delay(void)

{

unsigned char time;

for(time=0; time<120; time++);

}

Line Laser Module

Changchun Realpoo is a professional manufacture of laser modules in the world. Our company possess experienced engineer, Professional production line,excellent testing machine as well as advanced instrument. With the advantages,we offer Laser Module,laser diode,laser lamp,laser stage lamp,laser
peripheral product,PCB circuit design and development and so on. We can ensure higher qualified rate.

Line Laser Module,Line Laser,Line Laser Light,Line Laser Module

Changchun Realpoo Photoelectric Co., Ltd. , https://www.optics-realpoo.com