LED sequence control using a button

LED sequence control using a button

Main Diagram

Hardware Required

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

Description

A counter is used to track which LED to light. On each valid press (rising edge), the counter increases and the LEDs change accordingly. The sequence loops after reaching the last state.

• 1st press → Red LED ON
• 2nd press → Yellow LED ON
• 3rd press → Green LED ON
• 4th press → All OFF (or repeat from beginning)

We use a pull-down resistor to keep the button input LOW when not pressed

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 LEDs Red, Yellow, Green to GPIO 8,9,10 respectively through a 220Ω resistor.
  • Connect the cathode (short leg) of the LEDs to GND.
  • Connect one leg of the push button to 3.3V.
  • Connect the other leg of the button to GPIO 7.
  • Connect one end of the 10kΩ resistor to GPIO 7 and other end to GND.

Schematic

Button one side → 3.3V

Other side → GPIO 7

GPIO 7 → 10kΩ → GND

GPIO 8 → 220Ω → Red LED anode

GPIO 9 → 220Ω → Yellow LED anode

GPIO 10 → 220Ω → Green LED anode

LEDs cathode → GND

Code - C

#define BUTTON_PIN 7

int leds[] = {8, 9, 10};
int count = 0;
bool prevState = false;

void setup() {
  pinMode(BUTTON_PIN, INPUT);
  for (int i = 0; i < 3; i++) {
    pinMode(leds[i], OUTPUT);
  }
}

void loop() {
  bool state = digitalRead(BUTTON_PIN);

  if (state == HIGH && prevState == LOW) {
    count = (count + 1) % 4;

    for (int i = 0; i < 3; i++) {
      digitalWrite(leds[i], (count == i + 1) ? HIGH : LOW);
    }

    delay(200); // Debounce delay
  }

  prevState = state;
  delay(10);
}
int leds[] = {8, 9, 10} - List of LED output pins.

Count - Tracks which LED to turn on.

if (state == HIGH && prevState == LOW) - Rising edge detection for single press.

count = (count + 1) % 4 - Advances to the next LED, loops after all.

delay(200) - Debounce delay to avoid double counting.

Code - Micropython

from machine import Pin
import time

leds = [Pin(8, Pin.OUT), Pin(9, Pin.OUT), Pin(10, Pin.OUT)]
button = Pin(7, Pin.IN)

count = 0
prev_state = 0

while True:
    state = button.value()

    if state == 1 and prev_state == 0:
        count = (count + 1) % 4

        for i in range(3):
            leds[i].value(1 if count == i + 1 else 0)

        time.sleep(0.2)  # Debounce delay

    prev_state = state
    time.sleep(0.01)
leds = [...] - Stores LED pins in a list for easy access.

count = 0 - Keeps track of how many times the button has been pressed.

count = (count + 1) % 4 - Increments counter and resets it after reaching 3.

leds[i].value(1 if count == i + 1 else 0) - Turns ON the selected LED and OFF the others.

time.sleep(0.2) - Adds a debounce delay to avoid double counting.