Circuits--Sequential--Finite5

时间:2024-04-29 09:17:34

1. Design a moore FSM

module top_module (
    input clk,
    input reset,
    input [3:1] s,
    output fr3,
    output fr2,
    output fr1,
    output dfr
); 
    
    parameter A2=3'd0;
    parameter B1=3'd1;
    parameter B2=3'd2;
    parameter C1=3'd3;
    parameter C2=3'd4;
    parameter D1=3'd5;
    
    reg[2:0] state;
    reg[2:0] next_state;
    
    always @(*)begin
        case(state)
            A2:next_state = s[1]?B1:A2;
            B1:next_state = s[2]?C1:(s[1]?B1:A2);
            B2:next_state = s[2]?C1:(s[1]?B2:A2);
            C1:next_state = s[3]?D1:(s[2]?C1:B2);
            C2:next_state = s[3]?D1:(s[2]?C2:B2);
            D1:next_state = s[3]?D1:C2;
            default:next_state = 'x;
        endcase
    end
    
    always @(posedge clk)begin
        if(reset)begin
        	state <= A2;
        end
        else begin
        	state <= next_state;
        end
    end
    
    always @(*)begin
        case(state)
            A2:{fr3,fr2,fr1,dfr} = 4'b1111;
            B1:{fr3,fr2,fr1,dfr} = 4'b0110;
            B2:{fr3,fr2,fr1,dfr} = 4'b0111;
            C1:{fr3,fr2,fr1,dfr} = 4'b0010;
            C2:{fr3,fr2,fr1,dfr} = 4'b0011;
            D1:{fr3,fr2,fr1,dfr} = 4'b0000;
            default:{fr3,fr2,fr1,dfr} = 'x;
        endcase
    end

endmodule

2. Lemmings1

module top_module(
    input clk,
    input areset,    // Freshly brainwashed Lemmings walk left.
    input bump_left,
    input bump_right,
    output walk_left,
    output walk_right); //  

    // parameter LEFT=0, RIGHT=1, ...
    reg state, next_state;
    parameter left = 1'b0;
    parameter right = 1'b1;
    

    always @(*) begin
        case(state)
            left:
                begin
                    if(!bump_left)  next_state = left;
                    else next_state = right;
                end
            right:
                begin
                    if(!bump_right) next_state = right;
                    else next_state = left;
                end
        endcase
    end

    always @(posedge clk, posedge areset) begin
        // State flip-flops with asynchronous reset
        if(areset)
            state <= left;
        else
            state <= next_state;
    end

    // Output logic
    assign walk_left = (state == left);
    assign walk_right = (state == right);

endmodule