Named States With enum
Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 9 of 18.
A mode numbered 0, 1 and 2 works, but if (mode == 2) does not say what 2 means. An enum gives each number a name:
enum State { READY, RUNNING, DONE };
State state = READY;The first line makes a new type, State, whose only values are READY, RUNNING and DONE. Underneath they are still 0, 1 and 2, but the names say what each one means. The second line makes a variable of that type.
An enum and a switch fit together: one case per state.
switch (state) {
case READY:
// what READY does, and when it moves on
break;
case RUNNING:
// ...
break;
}To move to a new state, set state and remember when it began: state = DONE; stateStart = millis();. Each state then times itself with millis() - stateStart. This way of writing a sketch is called a state machine.
Challenge
MediumA machine has three states. READY is written for you: the green LED is on, and a press starts the machine. Add the other two cases:
RUNNING: the yellow LED is on. After 2000 ms, turn it off and go toDONE.DONE: the red LED is on. After 1000 ms, turn it off and go back toREADY.
Store stateStart on each change. Press Run, press the button, then Check.
Try it yourself
const int buttonPin = 2;
const int greenLed = 10;
const int yellowLed = 11;
const int redLed = 12;
enum State { READY, RUNNING, DONE };
State state = READY;
unsigned long stateStart = 0; // when the current state began
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(greenLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(redLed, OUTPUT);
}
void loop() {
unsigned long now = millis();
switch (state) {
case READY:
digitalWrite(greenLed, HIGH);
if (digitalRead(buttonPin) == LOW) {
digitalWrite(greenLed, LOW);
state = RUNNING;
stateStart = now;
}
break;
// add case RUNNING: yellow on; after 2000 ms, yellow off and go to DONE
// add case DONE: red on; after 1000 ms, red off and go back to READY
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Timing Without Delay
Practice on your own: Arduino playground