All submissions

LED Blinking Patterns

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

const int led_pins[] = { 2, 3, 4, 5 };
const int switch_pin = 12;

const int pattern_lengths[] = { 2, 2, 4, 2, 2 };
const int patterns[][4][4] = {  
    { { 1, 1, 1, 1 }, { 0, 0, 0, 0 } },
    { { 1, 0, 1, 0 }, { 0, 1, 0, 1 } },
    { { 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, 1 }, { 0, 1, 1, 0 } }
};

unsigned int flag_check = 1;
int pattern_index = 0;
unsigned long debounce_delay = 50;
int last_button_state = 1;
int current_button_state = 1;
unsigned long last_debounce_time = 0;

void setup() {
    for (int i = 0; i < 4; i++) {
        pinMode(led_pins[i], OUTPUT);
    }
    pinMode(switch_pin, INPUT_PULLUP);
}

void loop() {
    while (flag_check) {
        for (int j = 0; j < pattern_lengths[pattern_index]; j++) {
            set_leds(patterns[pattern_index][j]);
            flag_check = delay_with_button_check(500);
            if (!flag_check) break;
        }
        if (!flag_check) break;
    }
    flag_check = 1;
}

bool is_debounced_press(int button_pin) {
    int reading = digitalRead(button_pin); 

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

    if ((millis() - last_debounce_time) > debounce_delay) {
        if (reading != current_button_state) {
            current_button_state = reading;
            if (current_button_state == 0) {
                return true;
            }
        }
    }
    return false;
}

bool delay_with_button_check(long delay_duration) {
    long delay_start_time = millis();
    while ((millis() - delay_start_time) < delay_duration) {
        if (is_debounced_press(switch_pin)) {
            pattern_index = (pattern_index + 1) % 5;
            return false;
        }
    }
    return true;
}

void set_leds(const int states[]) {
  for (int i = 0; i < 4; i++) {
    digitalWrite(led_pins[i], states[i]);
  }
}


 

 

 

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!