All courses

Arduino C++ · Lesson 28 of 40

Turn behavior into a state machine

Responsive Timing and State Machines

Name the states before writing conditions

IDLEACTIVECOOLDOWNPress2 s1 s → IDLE
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;

void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  const unsigned long now = millis();
  const bool released = digitalRead(2) == HIGH;
  if (released && !wasReleased) releasedAt = now;
  if (released && now - releasedAt >= 30) armed = true;
  const bool 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.

Official references for further study

A useful reminder

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.