Bird
Raised Fist0
Arduinoprogramming~10 mins

State machine design for Arduino - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - State machine design for Arduino
Start
↓
Initialize State
↓
Read Inputs
↓
Check Current State
↓
If State A
↓
Stay in State A
↓
If State B
↓
Stay in State B
↓
Perform Actions
↓
Loop Back to Read Inputs
The Arduino program starts by setting an initial state, then repeatedly reads inputs, checks the current state, decides if it should change state based on conditions, performs actions for that state, and loops back.
Execution Sample
Arduino
enum State {IDLE, LED_ON};
State currentState = IDLE;

void setup() {
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  if (currentState == IDLE && digitalRead(2) == HIGH) {
    currentState = LED_ON;
  } else if (currentState == LED_ON && digitalRead(2) == LOW) {
    currentState = IDLE;
  }
  digitalWrite(13, currentState == LED_ON ? HIGH : LOW);
}
This code switches an LED on pin 13 on or off based on a button on pin 2 using a simple two-state machine.
Execution Table
StepcurrentStatedigitalRead(2)Condition CheckedState ChangeLED Output
1IDLELOWIDLE && HIGH? FalseNo changeLOW
2IDLEHIGHIDLE && HIGH? TrueChange to LED_ONHIGH
3LED_ONHIGHLED_ON && LOW? FalseNo changeHIGH
4LED_ONLOWLED_ON && LOW? TrueChange to IDLELOW
5IDLELOWIDLE && HIGH? FalseNo changeLOW
💡 Loop runs continuously; no exit in Arduino loop function.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5
currentStateIDLEIDLELED_ONLED_ONIDLEIDLE
digitalRead(2)N/ALOWHIGHHIGHLOWLOW
LED OutputLOWLOWHIGHHIGHLOWLOW
Key Moments - 3 Insights
Why does the LED turn on only when the button is pressed?
Because in the execution_table at Step 2, when digitalRead(2) is HIGH and currentState is IDLE, the state changes to LED_ON, which sets the LED output HIGH.
What happens if the button stays pressed for multiple loops?
As shown in Step 3, if the button remains HIGH and the state is LED_ON, no state change occurs, so the LED stays on.
Why is there no exit from the loop?
Arduino's loop() function runs forever, so the execution_table notes that the loop continues indefinitely, cycling through states based on input.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2. What is the currentState after this step?
ALED_ON
BIDLE
CHIGH
DLOW
💡 Hint
Check the 'State Change' column at Step 2 in the execution_table.
At which step does the LED turn off according to the execution_table?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look at the 'LED Output' column and find when it changes to LOW.
If digitalRead(2) is always LOW, what will be the currentState after Step 5?
ALED_ON
BIDLE
CHIGH
DUndefined
💡 Hint
Refer to the variable_tracker for currentState values when digitalRead(2) is LOW.
Concept Snapshot
State machine design in Arduino:
- Define states using enum or constants.
- Use a variable to track current state.
- In loop(), read inputs and check conditions.
- Change state based on conditions.
- Perform actions based on current state.
- Loop runs forever, updating state and outputs.
Full Transcript
This example shows how to design a simple state machine on Arduino. We start with an initial state called IDLE. The program reads a button input on pin 2. If the button is pressed (input HIGH) while in IDLE, the state changes to LED_ON, turning on an LED on pin 13. If the button is released (input LOW) while in LED_ON, the state changes back to IDLE, turning the LED off. The loop repeats forever, checking inputs and updating the state and LED accordingly. The execution table traces each step, showing the state, input, condition checks, state changes, and LED output. The variable tracker shows how currentState and LED output change over time. This design helps organize code clearly and makes it easy to add more states or inputs later.

Practice

(1/5)
1. What is the main purpose of using a state machine in an Arduino program?
easy
A. To organize the program into clear, manageable steps
B. To increase the speed of the Arduino processor
C. To reduce the power consumption automatically
D. To connect multiple Arduino boards together

Solution

  1. Step 1: Understand the concept of state machines

    A state machine breaks a program into distinct states or steps to manage behavior clearly.
  2. Step 2: Identify the main benefit in Arduino context

    This organization helps make the code easier to read, debug, and extend.
  3. Final Answer:

    To organize the program into clear, manageable steps -> Option A
  4. Quick Check:

    State machine purpose = organize steps [OK]
Hint: State machines organize code into clear steps [OK]
Common Mistakes:
  • Thinking state machines speed up the processor
  • Confusing power saving with state management
  • Assuming state machines connect multiple boards
2. Which of the following is the correct way to declare states in an Arduino state machine using enum?
easy
A. enum State {START, RUNNING, STOPPED};
B. enum State = {START, RUNNING, STOPPED};
C. enum State {START; RUNNING; STOPPED};
D. enum State (START, RUNNING, STOPPED);

Solution

  1. Step 1: Recall enum syntax in Arduino (C++)

    The correct syntax uses curly braces and commas to list states without assignment or semicolons.
  2. Step 2: Check each option for syntax errors

    enum State {START, RUNNING, STOPPED}; uses correct syntax: enum State {START, RUNNING, STOPPED}; Options B, C, and D have incorrect assignment, semicolons, or parentheses.
  3. Final Answer:

    enum State {START, RUNNING, STOPPED}; -> Option A
  4. Quick Check:

    Correct enum syntax = enum State {START, RUNNING, STOPPED}; [OK]
Hint: Use curly braces and commas for enum states [OK]
Common Mistakes:
  • Using '=' sign after enum name
  • Separating states with semicolons instead of commas
  • Using parentheses instead of braces
3. What will be the output on the Serial Monitor when running this Arduino code snippet?
enum State {IDLE, PROCESS, DONE};
State currentState = IDLE;

void setup() {
  Serial.begin(9600);
  switch(currentState) {
    case IDLE:
      Serial.println("Waiting");
      break;
    case PROCESS:
      Serial.println("Working");
      break;
    case DONE:
      Serial.println("Finished");
      break;
  }
}
medium
A. Finished
B. Working
C. Waiting
D. No output

Solution

  1. Step 1: Identify the initial state value

    The variable currentState is set to IDLE before setup() runs.
  2. Step 2: Follow the switch-case logic

    Switch checks currentState; since it is IDLE, it prints "Waiting" to Serial Monitor.
  3. Final Answer:

    Waiting -> Option C
  4. Quick Check:

    State IDLE prints "Waiting" [OK]
Hint: Check initial state value to predict output [OK]
Common Mistakes:
  • Assuming PROCESS or DONE prints without state change
  • Thinking setup() runs multiple times
  • Ignoring break statements in switch
4. Identify the error in this Arduino state machine code snippet:
enum State {START, RUNNING, STOPPED};
State currentState = START;

void loop() {
  switch(currentState) {
    case START:
      Serial.println("Start");
      currentState = RUNNING
      break;
    case RUNNING:
      Serial.println("Running");
      break;
    case STOPPED:
      Serial.println("Stopped");
      break;
  }
}
medium
A. Incorrect enum declaration
B. Serial not initialized in setup()
C. Missing break in RUNNING case
D. Missing semicolon after currentState = RUNNING

Solution

  1. Step 1: Check syntax line by line

    Look at the line: currentState = RUNNING without a semicolon at the end.
  2. Step 2: Identify the error type

    Missing semicolon causes a compile error. Other parts are correct or not critical for this snippet.
  3. Final Answer:

    Missing semicolon after currentState = RUNNING -> Option D
  4. Quick Check:

    Missing semicolon = syntax error [OK]
Hint: Check each statement ends with a semicolon [OK]
Common Mistakes:
  • Ignoring missing semicolon errors
  • Assuming enum declaration is wrong
  • Forgetting to initialize Serial in setup()
5. You want to design a state machine for an Arduino traffic light with states: RED, GREEN, YELLOW. Which approach correctly updates the state to cycle through RED -> GREEN -> YELLOW -> RED inside loop()?
hard
A. Use a while loop inside loop() to cycle states infinitely
B. Use a switch on currentState and set currentState to the next state in each case
C. Use if statements comparing currentState to integers 0,1,2 and increment currentState by 1
D. Use delay() to wait and then reset currentState to RED always

Solution

  1. Step 1: Understand state machine cycling

    Using a switch-case on currentState allows clear, readable transitions between states.
  2. Step 2: Evaluate each option's suitability

    Use a switch on currentState and set currentState to the next state in each case correctly updates currentState to the next state inside each case. Use if statements comparing currentState to integers 0,1,2 and increment currentState by 1 uses integers but lacks clarity and safe cycling. Use a while loop inside loop() to cycle states infinitely with while loop inside loop() blocks Arduino's main loop. Use delay() to wait and then reset currentState to RED always resets state always to RED, not cycling properly.
  3. Final Answer:

    Use a switch on currentState and set currentState to the next state in each case -> Option B
  4. Quick Check:

    Switch-case for cycling states = Use a switch on currentState and set currentState to the next state in each case [OK]
Hint: Use switch-case to update states clearly [OK]
Common Mistakes:
  • Using while loops inside loop() causing freezes
  • Resetting state without cycling
  • Using integers without clear state names
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard