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
enum Modegives the three states real names.- Each case checks its own exit condition and hands off.
started = millis()timestamps the transition for the timer.
Keywords and builtins used here
HIGHLOWModeOUTPUTanalogReadbreakcasedigitalWriteenumiflongloopmillispinModesetupswitchunsignedvoid
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.
Step 3 of 3 in Functions & state, step 18 of 27 in Language basics.