To solve this task, we will create a program that cycles through five distinct LED patterns controlled by a single push-button.
switch...case
statement will be used to select the correct LED pattern based on the counter's value.digitalWrite()
function will then be used to turn the appropriate LEDs on or off to display the current pattern.
/*Paste your code here*/
const int Button = 10;
const int Led1 = 6;
const int Led2 = 5;
const int Led3 = 4;
const int Led4 = 3;
int pattern = 1;
int lastReading = HIGH;
int buttonState = HIGH;
unsigned long lastDebounce = 0;
const unsigned long debounceDelay = 50;
unsigned long lastPatternMillis = 0;
bool phase = true;
int stepIndex = 0;
void setup() {
pinMode(Button, INPUT_PULLUP);
pinMode(Led1, OUTPUT);
pinMode(Led2, OUTPUT);
pinMode(Led3, OUTPUT);
pinMode(Led4, OUTPUT);
lastPatternMillis = millis();
applyPatternOutputs();
}
void loop() {
unsigned long now = millis();
int reading = digitalRead(Button);
if (reading != lastReading) lastDebounce = now;
if (now - lastDebounce > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == LOW) {
pattern++;
if (pattern > 5) pattern = 1;
phase = true;
stepIndex = 0;
lastPatternMillis = now;
applyPatternOutputs();
}
}
}
lastReading = reading;
unsigned long interval;
if (pattern == 1) {
interval = (phase ? 1000UL : 500UL);
} else {
interval = 500UL;
}
if (now - lastPatternMillis >= interval) {
lastPatternMillis = now;
if (pattern == 3) {
stepIndex++;
if (stepIndex > 3) stepIndex = 0;
applyPatternOutputs();
} else {
phase = !phase;
applyPatternOutputs();
}
}
}
void applyPatternOutputs() {
digitalWrite(Led1, LOW);
digitalWrite(Led2, LOW);
digitalWrite(Led3, LOW);
digitalWrite(Led4, LOW);
if (pattern == 1) {
if (phase) {
digitalWrite(Led1, HIGH);
digitalWrite(Led2, HIGH);
digitalWrite(Led3, HIGH);
digitalWrite(Led4, HIGH);
}
}
else if (pattern == 2) {
if (phase) {
digitalWrite(Led1, HIGH);
digitalWrite(Led3, HIGH);
} else {
digitalWrite(Led2, HIGH);
digitalWrite(Led4, HIGH);
}
}
else if (pattern == 3) {
if (stepIndex == 0) digitalWrite(Led1, HIGH);
else if (stepIndex == 1) digitalWrite(Led2, HIGH);
else if (stepIndex == 2) digitalWrite(Led3, HIGH);
else if (stepIndex == 3) digitalWrite(Led4, HIGH);
}
else if (pattern == 4) {
if (phase) {
digitalWrite(Led1, HIGH);
digitalWrite(Led2, HIGH);
} else {
digitalWrite(Led3, HIGH);
digitalWrite(Led4, HIGH);
}
}
else if (pattern == 5) {
if (phase) {
digitalWrite(Led1, HIGH);
digitalWrite(Led4, HIGH);
} else {
digitalWrite(Led2, HIGH);
digitalWrite(Led3, HIGH);
}
}
}
Add a video of the output (know more)