Keypad code lock
Implement a door lock that takes a 4-digit code, re-locks, and locks out after three failures. A hard embedded C problem (State machines), run and graded in…
hard · State machines · fsm · security · strings
lock_key handles one key press and returns the new state. Keys are '0' to '9', '*' and '#'; any other key is ignored.
- In
LOCK_IDLEorLOCK_ENTRY: - a digit is added to the entry and the state becomes
LOCK_ENTRY; '*'clears the entry and returns toLOCK_IDLE;'#'submits. Exactly four digits matchingcodeopen the lock (LOCK_OPEN) and resetfailures. Anything else, including more or fewer than four digits, is a wrong attempt: it clears the entry, adds a failure, and returns toLOCK_IDLE, or goes toLOCK_LOCKOUTon the third failure in a row.- In
LOCK_OPEN, any key re-locks: the state becomesLOCK_IDLE. - In
LOCK_LOCKOUT, every key is ignored.
Starter code
lock_state_t lock_key(lock_t *l, char key) {
if (key >= '0' && key <= '9') {
if (l->len < 4) l->entry[l->len++] = key;
l->state = LOCK_ENTRY;
} else if (key == '#') {
l->state = memcmp(l->entry, l->code, 4) == 0 ? LOCK_OPEN : LOCK_IDLE;
l->len = 0;
}
return l->state;
}Example tests
Correct code, then re-lock
lock_t l = make_lock("1234");
feed(&l, "1234#x");Expected output:
EEEEOIClear a mistake and try again
lock_t l = make_lock("1234");
feed(&l, "12*1234#");Expected output:
EEIEEEEOLearn it first
- State machine patterns in C · Switch, transition tables and state-function pointers compared.
More State machines problems
- Traffic light with a fault mode · Write the transition function for a light that cycles, flashes on a fault and resets.
- Table-driven state machine · Look up a transition in a table, run its action and return the next state.
- Garage door controller · Write the transition function of a garage door, including the obstacle safety reversal.
- Click, double-click and long press · Turn a sampled button into click, double-click and long-press events with a state machine.
- Fix: the door opens by itself · A door controller skips its unlocking state.
- Washing machine: the cycle and the door · Run a wash cycle as a state machine that pauses safely when the door opens.