Verilog状态机

以1011为例

代码如下:

//1011(Meay型)
module state1(clk,in,rst_n,out);
    input clk;
    input rst_n;
    input in;
    output reg out;
    reg [1:0] state;
    reg[1:0] s0=2'b00,s1=2'b01,s2=2'b10,s3=2'b11;
    (posedge clk or negedge rst_n)
        if(!rst_n) 
            begin
                state<=2'b00;
                out<=1'b0;
            end
        else
            begin
                case(state)
                    s0:
                        begin
                            state<=(in==0)? s0:s1;
                            out<=0;
                        end
                    s1:
                        begin
                            state<=(in==0)? s2:s1;
                            out<=0;
                        end
                    s2:
                        begin
                            state<=(in==0)? s0:s3;
                            out<=0;
                        end
                    s3:
                        if(in)
                            begin
                                state<=s1;
                                out<=1;
                            end
                        else
                            begin
                                state<=s2;
                                out<=0;
                            end
                    default:
                            begin
                                state<=s0;
                                out<=1;
                            end

                endcase
            end
endmodule