int ledPins[] = {7, 6, 5, 4, 3, 2, 1, 0};
int buttonPin = 8;
bool loopRunning = false;
int currentLED = 0; // Tracks the current LED
unsigned long previousMillis = 0;
const unsigned long interval = 1000; // 1 second interval (1000 milliseconds)
unsigned long buttonPressStartTime = 0; // To track when the button was pressed
const unsigned long holdDuration = 2000; // 2 seconds hold duration
bool buttonPreviouslyPressed = false; // To track button press state
void setup() {
for (int i = 0; i < 8; i++) {
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], 1); // Turn off all LEDs initially
}
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
}
void loop() {
bool currentButtonState = digitalRead(buttonPin);
// Check if the button state has changed
if (currentButtonState == LOW && !buttonPreviouslyPressed) {
buttonPressStartTime = millis(); // Record the time when button was first pressed
buttonPreviouslyPressed = true;
}
if (currentButtonState == HIGH && buttonPreviouslyPressed) {
// Button was released
unsigned long buttonPressDuration = millis() - buttonPressStartTime;
if (buttonPressDuration < holdDuration) {
// Button was pressed but not held for 2 seconds
loopRunning = !loopRunning; // Toggle the LED sequence
if (!loopRunning) {
digitalWrite(ledPins[currentLED], 0); // Keep the current LED on when stopped
}
}
buttonPreviouslyPressed = false;
}
if (loopRunning) {
unsigned long currentMillis = millis();
// Check if the interval has passed
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis; // Update the last change time
// Turn off the previous LED
digitalWrite(ledPins[currentLED], 1);
// Move to the next LED
currentLED++;
if (currentLED >= 8) {
currentLED = 0; // Reset to the first LED after the last one
}
// Turn on the current LED
digitalWrite(ledPins[currentLED], 0);
}
}
}