题目
地址:HDLBits - Lemmings2
详细:
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.
Module Declaration
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 );
分析
- 首先确认状态数量,本例中使用三个状态:LEFT-向左走,RIGHT-向右走,FALL-下落。并使用state,next_state和state_before_fall分别记录当前状态、下一状态和下落前的状态,下落前的状态用于ground为1后继续下落前的方向行走。
- state_before_fall使用时序逻辑描述,重置为LEFT状态,当时钟上升沿到来时,如果ground为0,且上升沿前为非FALL状态,将state赋值给state_before_fall;如果为FALL状态或者ground为1,state_before_fall保持不变,与当前状态不符合也没关系。
- 状态转移条件:ground为1时,正常判断,为0时下一状态为FALL。
- 摩尔型状态机输出只与当前状态相关。
代码
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=2'b00,RIGHT=2'b01,FALL=2'b11;
reg [1:0] state, next_state, state_before_fall;
always @(posedge clk,posedge areset) begin
if (areset)
state_before_fall <= LEFT;
else if (~ground && (state!=FALL))
state_before_fall <= state;
else
state_before_fall <= state_before_fall;
end
always @(*) begin
case (state)
LEFT: begin
if (ground) next_state = bump_left?RIGHT:LEFT;
else next_state = FALL;
end
RIGHT: begin
if (ground) next_state = bump_right?LEFT:RIGHT;
else next_state = FALL;
end
FALL: begin
if (ground) next_state = state_before_fall;
else next_state = FALL;
end
endcase
end
always @(posedge clk, posedge areset) begin
if (areset)
state <= LEFT;
else
state <= next_state;
end
assign walk_left = (state==LEFT)?1'b1:1'b0;
assign walk_right = (state==RIGHT)?1'b1:1'b0;
assign aaah = (state==FALL)?1'b1:1'b0;
endmodule