All submissions

Solving Approach

I connected 4 LEDs to digital output pins of the microcontroller and 1 push button to a digital input pin in Wokwi. The button is used to change patterns. In the Arduino code, I used a variable to keep track of which pattern is active. Every time the button is pressed, the variable increases and the program shifts the LEDs to the next pattern. After the last pattern, it goes back to the first one.

 

Code

#include <Arduino.h>

#define NUM_LEDS 4
#define NUM_PATTERNS 5
#define MAX_STEPS 4
#define SWITCH_PIN 12
#define DEBOUNCE_DELAY 50

const uint8_t led_pins[NUM_LEDS] = { 2, 3, 4, 5 };

// Use -1 as a sentinel for end of pattern
const int patterns[NUM_PATTERNS][MAX_STEPS][NUM_LEDS] = {
    { {1, 1, 1, 1}, {0, 0, 0, 0}, {-1, 0, 0, 0}, {-1, 0, 0, 0} },
    { {1, 0, 1, 0}, {0, 1, 0, 1}, {-1, 0, 0, 0}, {-1, 0, 0, 0} },
    { {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1} },
    { {1, 1, 0, 0}, {0, 0, 1, 1}, {-1, 0, 0, 0}, {-1, 0, 0, 0} },
    { {1, 0, 0, 1}, {0, 1, 1, 0}, {-1, 0, 0, 0}, {-1, 0, 0, 0} }
};

uint8_t pattern_index = 0;
uint8_t last_button_state = HIGH;
uint8_t current_button_state = HIGH;
unsigned long last_debounce_time = 0;

void setup() {
    for (uint8_t i = 0; i < NUM_LEDS; i++) {
        pinMode(led_pins[i], OUTPUT);
    }
    pinMode(SWITCH_PIN, INPUT_PULLUP);
}

void loop() {
    for (uint8_t j = 0; j < MAX_STEPS; j++) {
        if (patterns[pattern_index][j][0] == -1) break;
        set_leds(patterns[pattern_index][j]);

        if (!delay_with_button_check(500)) break;
    }
}

// Set LED states
void set_leds(const int states[]) {
    for (uint8_t i = 0; i < NUM_LEDS; i++) {
        digitalWrite(led_pins[i], states[i]);
    }
}

// Delay while checking button
bool delay_with_button_check(unsigned long duration) {
    unsigned long start_time = millis();
    while (millis() - start_time < duration) {
        if (is_debounced_press(SWITCH_PIN)) {
            pattern_index = (pattern_index + 1) % NUM_PATTERNS;
            return false;
        }
    }
    return true;
}

// Button debouncing
bool is_debounced_press(uint8_t button_pin) {
    uint8_t reading = digitalRead(button_pin);

    if (reading != last_button_state) {
        last_debounce_time = millis();
    }

    if ((millis() - last_debounce_time) > DEBOUNCE_DELAY) {
        if (reading != current_button_state) {
            current_button_state = reading;
            if (current_button_state == LOW) {
                last_button_state = reading;
                return true;
            }
        }
    }

    last_button_state = reading;
    return false;
}


 

 

 

Output

Video

Add a video of the output (know more)

 

 

 

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!