LED brightness control using multiple buttons

LED brightness control using multiple buttons

Main Diagram

Hardware Required

  • PICUNO Microcontroller board
  • 1 × LED
  • 1 × 220Ω resistor
  • 2 × Push Button (4-pin or 2-pin)
  • 2 × 10kΩ resistors
  • Breadboard
  • Jumper wires
  • USB cable

Description

This project uses two buttons to control the brightness of a single LED:

• Pressing Button 1 increases LED brightness by a step.
• Pressing Button 2 decreases LED brightness by a step.
• Pressing both resets brightness to 0.

We use a PWM-capable pin to control the LED brightness. The buttons are connected using pull-down resistors.

Circuit Diagram

[Fritzing image to be added here]

Circuit

  • Connect the PICUNO board to the computer using a USB cable.
  • Connect the anode (longer leg) of the LED to GPIO 8 through a 220Ω resistor.
  • Connect the cathode (short leg) of the LED to GND.
  • Connect one leg of the both push buttons 1 and 2 to 3.3V.
  • Connect the other leg of the buttons 1 and 2 to GPIO 6, 7 respectively.
  • Connect one end of the 10kΩ resistors to GPIO 6, 7 respectively and other end to GND.

Schematic

Button 1 one side → 3.3V

Other side → GPIO 6

Button 2 one side → 3.3V

Other side → GPIO 7

GPIO 6 → 10kΩ → GND

GPIO 7 → 10kΩ → GND

GPIO 8 → 220Ω → LED anode

LED cathode → GND

Code - C

#define LED_PIN 8
#define BUTTON_UP 6
#define BUTTON_DOWN 7

int brightness = 0;
const int step = 25;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_UP, INPUT);
  pinMode(BUTTON_DOWN, INPUT);
}

void loop() {
  bool up = digitalRead(BUTTON_UP);
  bool down = digitalRead(BUTTON_DOWN);

  if (up && down) {
    brightness = 0;
  } else if (up) {
    brightness = min(255, brightness + step);
  } else if (down) {
    brightness = max(0, brightness - step);
  }

  analogWrite(LED_PIN, brightness);
  delay(100);
}
brightness = 0 - Both buttons reset brightness.

min()/max() - Keep brightness in valid range.

delay(100) - Simple debounce and step control.

Code - Micropython

from machine import Pin, PWM
import time

led = PWM(Pin(8))
led.freq(1000)

button_up = Pin(6, Pin.IN)
button_down = Pin(7, Pin.IN)

brightness = 0
step = 5000

while True:
    if button_up.value() == 1 and button_down.value() == 1:
        brightness = 0
    elif button_up.value() == 1:
        brightness = min(65535, brightness + step)
    elif button_down.value() == 1:
        brightness = max(0, brightness - step)

    led.duty_u16(brightness)
    time.sleep(0.1)
PWM(Pin(8)) - Enables PWM on GPIO 8.

brightness - Variable holding current LED brightness.

step - Amount to increase or decrease brightness.

min() and max() used to clamp brightness within 0-65535.

led.duty_u16() - Updates PWM duty cycle.