// Exercise P6: your own FSM.  The worked example is a code lock that opens
// after the button gives 1, 0, 1 at three clock edges in a row, and stays
// open until reset.
//
// Generic version that matches schematic 1, not tied to any chip.  The
// first flip-flop samples the button: a is the button at the last clock
// edge, so the state machine works with a value that stays put for a whole
// clock cycle.  The state is the number of code digits matched so far:
// 0 nothing, 1 "1", 2 "1, 0", 3 open.  The next-state equations are the
// minimized ones of the FSM kit:
//
//     state [0]' = a | state [1] & state [0]
//     state [1]' = state [0] & ~ a | state [1] & a
//     open       = state [1] & state [0]
//
// rst clears everything at once, without the clock.  Synthesizable.

module code_lock
(
    input  logic       clk,
    input  logic       rst,
    input  logic       btn,
    output logic       a,      // the button, sampled
    output logic [1:0] state,
    output logic       open
);

    always_ff @ (posedge clk or posedge rst)
        if (rst)
        begin
            a     <= 1'b0;
            state <= 2'd0;
        end
        else
        begin
            a         <= btn;
            state [0] <= a | state [1] & state [0];
            state [1] <= state [0] & ~ a | state [1] & a;
        end

    assign open = state [1] & state [0];

endmodule
