RTL Design #63 · 2026-11-25 · FSM with a failure counter · Medium · about 25 min

A keypad lock with a lockout

Write keylock in lock.sv: the controller of a keypad lock with a 3-digit code 1, 3, 2. Each digit is 2 bits. A digit is entered on every rising edge where key_v is 1; edges with key_v 0 change nothing.

Attempts. The controller remembers how many digits of the code the current attempt has accepted.

  • A digit that matches the next digit of the code is accepted. When the third digit is accepted, unlock is 1 for exactly one cycle (the cycle after that edge), the attempt starts over, and the failure count (below) goes back to 0.
  • Any other digit is wrong. If the attempt had already accepted at least one digit, this is a failed attempt and the failure count goes up by one. A wrong digit on a fresh attempt (nothing accepted yet) is not a failure and is otherwise ignored.
  • After a wrong digit the attempt starts over, except that a wrong digit equal to 1 is itself the first digit of the new attempt.

Lockout. The third failed attempt in a row (no unlock in between) sets locked to 1 for 5 cycles, starting the cycle after that edge. While locked is 1, every digit is ignored. When the lockout ends, the attempt and the failure count are both 0. unlock is never 1 during a lockout.

Reset. rst_n is a synchronous active-low reset that clears everything, including a lockout in progress; unlock and locked are 0 afterwards.

Example: 1, 3, 2 on three consecutive key_v cycles gives unlock = 1 for one cycle. 1, 3, 0 is one failed attempt and unlock stays 0. 1, 1, 3, 2 unlocks: the second 1 was a wrong digit, but it counts as the start of a new attempt.

Fill in lock.sv. Run tries a few sequences.

Write and run your answer in the browser. The hidden tests check it, and it’s free.