Which of the following best explains why state machines are commonly used in embedded programming?
Think about how breaking down tasks into steps helps manage complexity.
State machines break down complex device behavior into simple states and clear rules for moving between them. This makes the code easier to read, debug, and maintain.
What will be the output of this embedded C code simulating a state machine?
typedef enum {IDLE, RUNNING, ERROR} State;
State current_state = IDLE;
void run_state_machine() {
switch(current_state) {
case IDLE:
printf("Idle state\n");
current_state = RUNNING;
break;
case RUNNING:
printf("Running state\n");
current_state = ERROR;
break;
case ERROR:
printf("Error state\n");
current_state = IDLE;
break;
}
}
int main() {
for(int i=0; i<3; i++) {
run_state_machine();
}
return 0;
}Look at how the state changes after each print.
The code starts in IDLE, prints "Idle state", then moves to RUNNING. Next, it prints "Running state" and moves to ERROR. Finally, it prints "Error state" and returns to IDLE.
What error will this embedded C code cause when run?
typedef enum {START, PROCESS, STOP} State;
State current_state = START;
void run_state_machine() {
switch(current_state) {
case START:
printf("Start\n");
current_state = PROCESS;
break;
case PROCESS:
printf("Process\n");
// Missing break here
case STOP:
printf("Stop\n");
current_state = START;
break;
}
}
int main() {
for(int i=0; i<4; i++) {
run_state_machine();
}
return 0;
}Check what happens when a break is missing in a switch-case.
Because the break is missing after PROCESS, the code falls through to STOP case, printing both "Process" and "Stop" each time PROCESS is reached.
Which of the following code snippets correctly updates the state variable in an embedded C state machine?
Remember the assignment operator in C.
In C, '=' is used to assign a value. '==' is a comparison, ':=' and '=>' are invalid syntax.
Given this embedded C code, how many unique states does the state machine have?
typedef enum {
INIT = 0,
WAIT = 1,
RUN = 2,
PAUSE = 3,
STOP = 4
} State;
State current_state = INIT;
void run_state_machine() {
switch(current_state) {
case INIT:
current_state = WAIT;
break;
case WAIT:
current_state = RUN;
break;
case RUN:
current_state = PAUSE;
break;
case PAUSE:
current_state = STOP;
break;
case STOP:
current_state = INIT;
break;
}
}Count all the enum values representing states.
The enum defines 5 states: INIT, WAIT, RUN, PAUSE, and STOP.