Question:(具体题目请参见HDLbits Lemmings1/2/3/4)Although Lemmings can walk, fall, and dig, Lemmings aren’t invulnerable. If a Lemming falls for too long then hits the ground, it can splatter. In particular, if a Lemming falls for more than 20 clock cycles then hits the ground, it will splatter and cease walking, falling, or digging (all 4 outputs become 0), forever (Or until the FSM gets reset). There is no upper limit on how far a Lemming can fall before hitting the ground. Lemmings only splatter when hitting the ground; they do not splatter in mid-air.
Extend your finite state machine to model this behaviour.
Falling for 20 cycles is survivable:
注意如果持续掉落,计数器就一直加大,因此cnt位宽要设置的足够大!(否则会发生相位截断错误),ground=1后仍保持cnt的值,同时将标志位单独assign。
module top_module(
input clk,
input areset, // Freshly brainwashed Lemmings walk left.
input bump_left,
input bump_right,
input ground,
input dig,
output walk_left,
output walk_right,
output aaah,
output digging );
parameter L=0,R=1,FL=2,FR=3,DL=4,DR=5,S=6;
reg [2:0]state,next;
int cnt;
reg s_flag;
always@(posedge clk,posedge areset)begin
if(areset)
cnt<=0;
else if(ground==0)
cnt<=cnt+1;
else if(cnt>20)
cnt<=cnt;
else cnt<=0;
end
assign s_flag=(cnt>20);
always@(*)begin
case(state)
L:next=ground?(dig?DL:(bump_left?R:L)):FL;
R:next=ground?(dig?DR:(bump_right?L:R)):FR;
FL:next=ground?(s_flag?S:L):FL;
FR:next=ground?(s_flag?S:R):FR;
DL:next=ground?DL:FL;
DR:next=ground?DR:FR;
S:next=S;
endcase
end
always@(posedge clk,posedge areset)begin
if(areset)
state<=L;
else
state<=next;
end
assign walk_left=!(state==S)&&(state==L);
assign walk_right=!(state==S)&&(state==R);
assign aaah=!(state==S)&&((state==FL)||(state==FR));
assign digging=!(state==S)&&((state==DL)||(state==DR));
endmodule