Control LED brightness on Arduino Uno using two buttons with PWM on pin 9 and software debounce for smooth increase and decrease in steps of 15.
// LED brightness control with two buttons
// Button on D2 increases brightness
// Button on D3 decreases brightness
const int ledPin = 9; // PWM pin connected to LED
const int btnUpPin = 2; // Button to increase brightness
const int btnDownPin = 3; // Button to decrease brightness
int brightness = 0; // Brightness value (0-255)
const int step = 15; // Brightness increment/decrement
// Variables for debounce management
unsigned long lastDebounceTimeUp = 0;
unsigned long lastDebounceTimeDown = 0;
const unsigned long debounceDelay = 50; // ms
int lastButtonUpState = LOW;
int lastButtonDownState = LOW;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(btnUpPin, INPUT);
pinMode(btnDownPin, INPUT);
analogWrite(ledPin, brightness); // LED initially off
}
void loop() {
// Read increase button state
int readingUp = digitalRead(btnUpPin);
if (readingUp != lastButtonUpState) {
lastDebounceTimeUp = millis();
}
if ((millis() - lastDebounceTimeUp) > debounceDelay) {
if (readingUp == HIGH) {
brightness += step;
if (brightness > 255) brightness = 255;
analogWrite(ledPin, brightness);
}
}
lastButtonUpState = readingUp;
// Read decrease button state
int readingDown = digitalRead(btnDownPin);
if (readingDown != lastButtonDownState) {
lastDebounceTimeDown = millis();
}
if ((millis() - lastDebounceTimeDown) > debounceDelay) {
if (readingDown == HIGH) {
brightness -= step;
if (brightness < 0) brightness = 0;
analogWrite(ledPin, brightness);
}
}
lastButtonDownState = readingDown;
delay(10); // Small pause for stability
}Arduino Uno (x1)
5mm LED (x1)
220Ω Resistor (x1)
Button (x2)
10kΩ Resistors (x2) for pull-down
CONNECTIONS: LED Cathode -> GND
CONNECTIONS: LED Anode -> 220Ω Resistor -> Arduino Pin D9
CONNECTIONS: Increase Button -> Arduino Pin D2 and GND via 10kΩ resistor (pull-down)
CONNECTIONS: Decrease Button -> Arduino Pin D3 and GND via 10kΩ resistor (pull-down)