Verilog刷题HDLBits——Lemmings2

Verilog刷题HDLBits——Lemmings2

  • 题目描述
  • 代码
  • 结果

题目描述

See also: Lemmings1.

In addition to walking left and right, Lemmings will fall (and presumably go “aaah!”) if the ground disappears underneath them.

In addition to walking left and right and changing direction when bumped, when ground=0, the Lemming will fall and say “aaah!”. When the ground reappears (ground=1), the Lemming will resume walking in the same direction as before the fall. Being bumped while falling does not affect the walking direction, and being bumped in the same cycle as ground disappears (but not yet falling), or when the ground reappears while still falling, also does not affect the walking direction.

Build a finite state machine that models this behaviour.
Verilog刷题HDLBits——Lemmings2_第1张图片
Verilog刷题HDLBits——Lemmings2_第2张图片

代码

module top_module(
    input clk,
    input areset,    // Freshly brainwashed Lemmings walk left.
    input bump_left,
    input bump_right,
    input ground,
    output walk_left,
    output walk_right,
    output aaah ); 
    
    parameter LEFT=0,RIGHT=1,FALL_L=2,FALL_R=3;
    reg[1:0] state,next_state; // 注意有四种状态
    
    always@(*)
        case(state)
            LEFT:if(~ground)
                	next_state=FALL_L;
            	else if(bump_left)
                    next_state=RIGHT;
            	else
                    next_state=LEFT;
            RIGHT:if(~ground)
                	next_state=FALL_R;
            	else if(bump_right)
                    next_state=LEFT;
            	else
                    next_state=RIGHT;
            FALL_L:next_state=ground?LEFT:FALL_L;
            FALL_R:next_state=ground?RIGHT:FALL_R;
        endcase
    
    always@(posedge clk or posedge areset)
        if(areset)
            state<=LEFT;
    	else
            state<=next_state;
    
    assign walk_left = (state==LEFT);
    assign walk_right = (state==RIGHT);
    assign aaah = (state==FALL_L)|(state==FALL_R);

endmodule

结果

Verilog刷题HDLBits——Lemmings2_第3张图片

你可能感兴趣的:(fpga开发)