Consider this Arduino code snippet implementing a simple state machine with three states. What will be printed to the Serial Monitor after 5 iterations of loop()?
enum State {IDLE, RUNNING, STOPPED};
State currentState = IDLE;
void setup() {
Serial.begin(9600);
}
void loop() {
switch(currentState) {
case IDLE:
Serial.println("Idle state");
currentState = RUNNING;
break;
case RUNNING:
Serial.println("Running state");
currentState = STOPPED;
break;
case STOPPED:
Serial.println("Stopped state");
currentState = IDLE;
break;
}
delay(10); // simulate some delay
}Look at how the currentState changes after each loop() call.
The state machine cycles through IDLE, RUNNING, and STOPPED states in order. Each loop() call prints the current state and moves to the next. After 5 iterations, the output matches option D.
In an Arduino state machine, what is the main purpose of using a switch statement inside the loop() function?
Think about how the program decides what to do next depending on the state.
The switch statement checks the current state and runs the code specific to that state, enabling the state machine to behave differently depending on its state.
What error will this Arduino code produce when compiled?
enum State {START, PROCESS, END};
State currentState = START;
void setup() {
Serial.begin(9600);
}
void loop() {
switch(currentState) {
case START:
Serial.println("Start");
currentState = PROCESS;
break;
case PROCESS:
Serial.println("Process");
currentState = END;
break;
case END:
Serial.println("End");
currentState = START;
break;
}
delay(1000);
}Check the syntax carefully after each break statement.
The break statement in the START case is missing a semicolon, causing a syntax error during compilation.
You design a traffic light controller with states: RED, RED_YELLOW, GREEN, and YELLOW. How many states should the enum have to represent this system?
Count each unique light combination as one state.
Each unique light combination is a state. Since there are four combinations, the enum should have 4 states.
What will be the output on the Serial Monitor after running this Arduino code for 3 iterations of loop()?
enum State {WAIT, ACTION};
State currentState = WAIT;
int counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
switch(currentState) {
case WAIT:
Serial.print("Waiting ");
Serial.println(counter);
if (counter >= 2) {
currentState = ACTION;
} else {
counter++;
}
break;
case ACTION:
Serial.println("Action executed");
currentState = WAIT;
counter = 0;
break;
}
delay(10);
}Trace the value of counter and state changes carefully.
On the first loop, counter is 0 and state is WAIT, prints "Waiting 0" and increments counter to 1.
Second loop prints "Waiting 1" and increments counter to 2.
Third loop prints "Waiting 2" because counter is 2 or more, then sets currentState to ACTION.