Each transition has a specific event or timeout. The LED is on only in ACTIVE.
A state machine separates what a system is doing from the events that change it. For a button-triggered indicator, use IDLE, ACTIVE, and COOLDOWN. An IDLE press activates the LED for two seconds; ACTIVE times out to COOLDOWN; after one second COOLDOWN returns to IDLE. Presses during ACTIVE or COOLDOWN are ignored.
Write a transition table before code. For every state list the accepted event, next state, and output. This prevents unrelated if statements from undoing each other in a single loop.
Implement one transition per loop
This complete example uses D2 to GND with INPUT_PULLUP and the onboard LED. It requires a released button for 30 ms before accepting a press; reuse the previous lesson's full debounce filter when noisy switches require it.
Arduino C++
enum class State { Idle, Active, Cooldown };
State state = State::Idle;
unsigned long enteredAt =0;
unsigned long releasedAt =0;
bool wasReleased = false;
bool armed = false;
voidsetup() {
pinMode(2, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
}
voidloop() {
const unsigned long now =millis();
constbool released =digitalRead(2) ==HIGH;
if (released && !wasReleased) releasedAt = now;
if (released && now - releasedAt >=30) armed = true;
constbool pressed = !released && armed;
if (!released) armed = false;
wasReleased = released;
switch (state) {
case State::Idle:if (pressed) { state = State::Active; enteredAt = now; }
break;
case State::Active:if (now - enteredAt >=2000) {
state = State::Cooldown; enteredAt = now;
}
break;
case State::Cooldown:if (now - enteredAt >=1000) state = State::Idle;
break;
}
digitalWrite(LED_BUILTIN, state == State::Active);
}
enteredAt records entry into the timed state. Output is derived from state in one place, rather than scattered through multiple branches.
Test: Press, release, and press again during ACTIVE: the two-second period should not restart. Hold the button through COOLDOWN: the next activation must wait for release and a new press. Draw a fourth FAULT state that can be entered from any state; identify which event is allowed to clear it.
Clean Code: Use descriptive constants instead of magic numbers
Instead of calling digitalWrite(13, HIGH) directly in your code, define descriptive constants like const int LED_PIN = 13; at the top of your file. This makes your code self-documenting and extremely easy to update if you change your wiring.