题解 | #根据状态转移写状态机-二段式#

根据状态转移写状态机-二段式

https://www.nowcoder.com/practice/5b2ff27610d04993ae92374d51bfc2e6

`timescale 1ns/1ns

module fsm2(
    input clk,
    input rst,
    input data,

    output reg flag
    );

    reg [2:0] current_state;
    reg [2:0] next_state;

    parameter   S0 = 3'b000;
    parameter   S1 = 3'b001;
    parameter   S2 = 3'b010;
    parameter   S3 = 3'b011;
    parameter   S4 = 3'b100;

    always@(posedge clk or negedge rst) begin
        if(!rst)
            current_state <= 3'd0;
        else
            current_state <= next_state;
    end

    always@(*) begin
        case(current_state) 
            S0: begin
                if(!rst)
                    next_state <= 3'd0;
                else if(data == 1)
                    next_state <= S1;
                else
                    next_state <= 3'd0;
            end
            S1: begin
                if(data == 1)
                    next_state <= S2;
                else
                    next_state <= S1;
            end
            S2: begin
                if(data == 1)
                    next_state <= S3;
                else
                    next_state <= S2;
            end
            S3: begin
                if(data == 1)
                    next_state <= S4;
                else
                    next_state <= S0;
            end
            S4: begin
                if(data == 1)
                    next_state <= S1;
                else
                    next_state <= S0;
            end
        endcase
end
    always@(posedge clk or negedge rst) begin
        if(!rst)
            flag <= 1'b0;
        else if(next_state == S4)
            flag <= 1'b1;
        else
            flag <= 1'b0;
    end
endmodule
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务