State transition function
Implement the transition rules of a motor controller. A medium embedded C problem (Function pointers and state machines), run and graded in the browser.
medium · Function pointers and state machines · state-machine
A motor controller is a state machine with these transitions:
ST_IDLE+EV_STARTgoes toST_RUNNINGST_RUNNING+EV_STOPgoes toST_IDLEST_RUNNING+EV_OVERCURRENTgoes toST_FAULTST_FAULT+EV_RESETgoes toST_IDLE
Every other combination leaves the state unchanged. In particular a fault is latched: only EV_RESET clears it. Return the next state.
Starter code
state_t fsm_step(state_t state, event_t event) {
// Return the state that follows `state` when `event` arrives.
return state;
}Example tests
Start then stop
state_t s = fsm_step(ST_IDLE, EV_START);
printf("%d", s);
s = fsm_step(s, EV_STOP);
printf(" %d\n", s);Expected output:
1 0Fault is latched
state_t s = fsm_step(ST_RUNNING, EV_OVERCURRENT);
printf("%d", s);
s = fsm_step(s, EV_START);
printf(" %d\n", s);Expected output:
2 2Learn it first
- Function pointers and callbacks · Callbacks, dispatch tables and the context pointer that makes them reusable.
More Function pointers and state machines problems
- Dispatch through a vector table · Call the handler registered for an interrupt number, with a safe fallback.
- Replace a switch with a table · Select an operation by opcode using an array of function pointers.
- Apply a function to a buffer · Transform every element of an array with a caller-supplied function.
- Command table lookup · Find a command by name in a table and call its handler.
- Sort with a comparator · Sort an array into an order defined by a callback.
- Publish and subscribe · Keep a fixed-size list of callbacks and notify them in order.
- Callback with context · Invoke a callback for every set bit, passing through a user context.
- Generic minimum · Find the smallest element of an array of any type using a comparator.
- State handlers · Build a state machine in which each state is a function.
- TV remote: a table of key actions · Look a key code up in a table and call its action with the device's context.