经典三段式状态机,此题采用了独热码。

`timescale 1ns/1ns

module det_moore(
   input                clk   ,
   input                rst_n ,
   input                din   ,
 
   output	reg         Y   
);
    reg [4:0] state, next_state;
    parameter S0 = 5'b00001,
              S1 = 5'b00010,
              S2 = 5'b00100,
              S3 = 5'b01000,
              S4 = 5'b10000;
    
    always@(posedge clk or negedge rst_n)
        if(!rst_n)
            state <= S0;
        else
            state <= next_state;
    
    always@(*)
        case(state)
            S0: next_state <=  din ? S1 : S0;
            S1: next_state <=  din ? S2 : S0;
            S2: next_state <= ~din ? S3 : S2;
            S3: next_state <=  din ? S4 : S0;
            S4: next_state <=  din ? S1 : S0;
            default: next_state <= S0;
        endcase
    
    always@(posedge clk or negedge rst_n)
        if(!rst_n)
            Y <= 1'b0;
        else if(state == S4)
            Y <= 1'b1;
        else
            Y <= 1'b0;

endmodule