typestar

A state machine in Arduino

An enum names the states; switch runs exactly one per pass.

// An enum names the states; switch runs exactly one per pass.
enum Mode { IDLE, WATERING, DRAINING };
Mode mode = IDLE;
unsigned long started = 0;

void setup() {
  pinMode(7, OUTPUT);
}

void loop() {
  switch (mode) {
    case IDLE:
      if (analogRead(A0) > 700) { mode = WATERING; started = millis(); }
      break;
    case WATERING:
      digitalWrite(7, HIGH);
      if (millis() - started > 3000) mode = DRAINING;
      break;
    case DRAINING:
      digitalWrite(7, LOW);
      if (analogRead(A0) < 500) mode = IDLE;
      break;
  }
}

How it works

  1. enum Mode gives the three states real names.
  2. Each case checks its own exit condition and hands off.
  3. started = millis() timestamps the transition for the timer.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
481
Tokens
124
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 124 seconds.

Type this snippet

Step 3 of 3 in Functions & state, step 18 of 27 in Language basics.

← Previous Next →