HDLbits Lemmings4
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:

Falling for 21 cycles causes splatter:

分析:该题其实就是一个状态机的题,相比于常规的状态机(需要计算下一个状态、交换状态、输出状态三个阶段),这里多出了一个下落周期的计算,这个下落周期用一个counter便可以解决。
【注意】counter虽说在计算下一个状态阶段需要拿出来判断是否达到splatter的要求,但是不会放在这个阶段内进行计数,因为该阶段与周期无关,若将counter放在该阶段内,则会报错。于是我们可以将counter单独用一个always块装着,这样也方便以后的修改。
代码如下:
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 left=0,right=1,falll=2,fallr=3,digl=4,digr=5,die=6;
reg [2:0] state,nstate;
int counter;
//状态交换
always @(posedge clk or posedge areset) begin
if(areset)
state <= left;
else
state <= nstate;
end
//计数器
always @(posedge clk or posedge areset) begin
if(areset)
counter <= 0;
else if(nstate==fallr||nstate==falll) begin
counter <= counter+1;
end
else if(counter > 20)
counter <= counter;
else
counter <= 0;
end
//下一个状态
always @(*) begin
case(state)
left: nstate = ground?(dig?digl:(bump_left?right:left)):falll;
right: nstate = ground?(dig?digr:(bump_right?left:right)):fallr;
falll: nstate = ground?((counter>20)?die:left):falll;
fallr: nstate = ground?((counter>20)?die:right):fallr;
digl: nstate = ground?digl:falll;
digr: nstate = ground?digr:fallr;
die: nstate = die;
default: nstate = 3'bx;
endcase
end
//状态输出
assign walk_left = (state == left)&&!(state == die);
assign walk_right = (state == right)&&!(state == die);
assign aaah = (state == fallr)||(state == falll)&&!(state == die);
assign digging = (state == digr)||(state == digl)&&!(state == die);
endmodule
本文介绍如何使用状态机实现HDLbits Lemmings4挑战中关于Lemming掉落超过20个时钟周期后死亡的逻辑。通过增加一个计数器来跟踪Lemming的下落时间,并在超过阈值时改变状态。

1172

被折叠的 条评论
为什么被折叠?



