为直观易于理解,状态机采用三段式写法,每个转移条件单独给出。输出需使用逻辑电路, 使用时序电路会比参考波形晚一个时钟周期。
注意:在设计状态机时需要充分考虑转换条件和优先级问题。
链接:https://hdlbits.01xz.net/wiki/Lemmings1
Lemmings1
当前进方向发生碰撞时调转方向
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 S0 = 1, S1 = 0;
wire S02S1;
wire S12S0;
assign S02S1 = bump_left == 1;
assign S12S0 = bump_right == 1;
always @(*) begin
// State transition logic
case(state)
S0:begin
if(S02S1)
next_state = S1;
else
next_state = state;
end
S1:begin
if(S12S0)
next_state = S0;
else
next_state = state;
end
endcase
end
always @(posedge clk, posedge areset) begin
// State flip-flops with asynchronous reset
if(areset)
state <= S0;
else
state <= next_state;
end
assign walk_left = (state == S0);
assign walk_right = (state == S1);
endmodule
Lemmings2
增加ground输入和aaah输出,当ground=0(没有地面)时,坠落aaah=1(结束游戏);当地面恢复时,回到坠落前的前进方向。
注意:左右方向转换的条件中ground=1是必要的,即只有在有地面时才可能有方向变换
Lemmings2 状态转换图
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 );
reg [3:0] state_c, state_n;
parameter left = 0, right = 1, leftgr = 2, rightgr = 3;
wire left2right, right2left, leftgr2left, left2leftgr, right2rightgr, rightgr2right;
always@(posedge clk or posedge areset) begin
if(areset)
state_c <= left;
else
state_c <= state_n;
end
always@(*) begin
case (state_c)
left:begin