// Week 4 - XIAO RP2040 // Modified version: stable button (INPUT_PULLUP), press-event trigger, no delay (millis), LED array const uint8_t LEDS[] = {D0, D6, D7}; const uint8_t NLEDS = sizeof(LEDS) / sizeof(LEDS[0]); const uint8_t BUTTON_PIN = D1; // button to GND const unsigned long STEP_MS = 250; // speed of the animation const int CYCLES_TO_RUN = 7; // how many times the pattern repeats // Debounce int lastReading = HIGH; int stableState = HIGH; unsigned long lastDebounceTime = 0; const unsigned long DEBOUNCE_MS = 30; // Sequence state machine bool running = false; int cycleCount = 0; int stepIndex = 0; // 0..(2*NLEDS - 1) unsigned long lastStepTime = 0; void allOff() { for (uint8_t i = 0; i < NLEDS; i++) digitalWrite(LEDS[i], LOW); } void setup() { Serial.begin(9600); for (uint8_t i = 0; i < NLEDS; i++) pinMode(LEDS[i], OUTPUT); pinMode(BUTTON_PIN, INPUT_PULLUP); // more stable allOff(); Serial.println("RP2040 ready. Press the button to run the LED sequence."); } void startSequence() { running = true; cycleCount = 0; stepIndex = 0; lastStepTime = millis(); allOff(); Serial.println("Button pressed -> starting sequence"); } void updateSequence() { if (!running) return; unsigned long now = millis(); if (now - lastStepTime < STEP_MS) return; lastStepTime = now; // Pattern: turn ON LEDs forward, then turn OFF LEDs backward if (stepIndex < NLEDS) { digitalWrite(LEDS[stepIndex], HIGH); } else { int offIdx = (2 * NLEDS - 1) - stepIndex; digitalWrite(LEDS[offIdx], LOW); } stepIndex++; // End of one full cycle if (stepIndex >= 2 * NLEDS) { stepIndex = 0; cycleCount++; Serial.print("Cycle: "); Serial.println(cycleCount); if (cycleCount >= CYCLES_TO_RUN) { running = false; allOff(); Serial.println("Sequence finished."); } } } void loop() { // ----- Debounced button reading ----- int reading = digitalRead(BUTTON_PIN); if (reading != lastReading) { lastDebounceTime = millis(); lastReading = reading; } if (millis() - lastDebounceTime > DEBOUNCE_MS) { if (reading != stableState) { stableState = reading; // Press event (INPUT_PULLUP => pressed = LOW) if (stableState == LOW) { if (!running) startSequence(); else Serial.println("Sequence already running..."); } } } // ----- Run the LED animation without blocking ----- updateSequence(); }