Simvik

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_IDLE or LOCK_ENTRY:
  • a digit is added to the entry and the state becomes LOCK_ENTRY;
  • '*' clears the entry and returns to LOCK_IDLE;
  • '#' submits. Exactly four digits matching code open the lock (LOCK_OPEN) and reset failures. Anything else, including more or fewer than four digits, is a wrong attempt: it clears the entry, adds a failure, and returns to LOCK_IDLE, or goes to LOCK_LOCKOUT on the third failure in a row.
  • In LOCK_OPEN, any key re-locks: the state becomes LOCK_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:

EEEEOI

Clear a mistake and try again

lock_t l = make_lock("1234");
feed(&l, "12*1234#");

Expected output:

EEIEEEEO

Learn it first

More State machines problems