In this post, we will see how we can control brightness of LED.
I am using 2 inputs for controlling, inreasing and decreasing.
One LED for output.
Find the code below.
//Controlling LED brightness with two input buttons
//Code by Deepak Sharma [ElectroMech Lab]
const int ledPin = 3; // LED connected to pin 3
const int buttonUpPin = 2; // Button to increase brightness connected to pin 2
const int buttonDownPin = 12; // Button to decrease brightness connected to pin 12
int brightness = 128; // Initial brightness (range from 0 to 255)
const int brightnessStep = 5; // Step to increase/decrease brightness
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonUpPin, INPUT_PULLUP);
pinMode(buttonDownPin, INPUT_PULLUP);
analogWrite(ledPin, brightness); // Set initial brightness
}
void loop() {
if (digitalRead(buttonUpPin) == LOW) { // Button is pressed (active low)
brightness += brightnessStep; // Increase brightness
if (brightness > 255) {
brightness = 255; // Cap the maximum brightness
}
analogWrite(ledPin, brightness); // Update LED brightness
delay(100); // Debounce delay
}
if (digitalRead(buttonDownPin) == LOW) { // Button is pressed (active low)
brightness -= brightnessStep; // Decrease brightness
if (brightness < 0) {
brightness = 0; // Cap the minimum brightness
}
analogWrite(ledPin, brightness); // Update LED brightness
delay(100); // Debounce delay
}
}
Comments
Post a Comment