题目描述:
Consider a finite state machine with inputs s and w. Assume that the FSM begins in a reset state called A, as depicted below. The FSM remains in state A as long as s = 0, and it moves to state B when s = 1. Once in state B the FSM examines the value of the input w in the next three clock cycles. If w = 1 in exactly two of these clock cycles, then the FSM has to set an output z to 1 in the following clock cycle. Otherwise z has to be 0. The FSM continues checking w for the next three clock cycles, and so on. The timing diagram below illustrates the required values of z for different values of w.
Use as few states as possible. Note that the s input is used only in state A, so you need to consider just the w input.
翻译:考虑一个输入为s和w的有限状态机。假设该状态机初始状态为A,描述如下:该状态机在s=0时维持A状态,并在s=1时切换至B状态。而一旦进入B状态,有限状态机就会检测接下来的三个时钟周期,若其中当且仅当两个周期输入为1,则下一个时钟周期将输出z置1,否则置0,有限状态机将继续检查输入w接下来的三个周期,下面的示图表明了不同w值对应的z值。
使用尽可能少的状态,s只在状态A中用到,因此只需考虑w的输入即可。
题目分析:在解此题时,参考了不少CSDN上的其他作者的答案,但均说本题作者的testbench有问题,并给出了错误的时序图。但其实是理解错了题目,或是没有正确建立状态机。并且还存在着好几个作者犯了同样的错误,连出错的时序图都一样,很难不怀疑是互相抄袭。本题有限状态机如下:
当s=0时,A状态循环,当s=1时,清零计数器,进入B状态。当处于B状态时并且计数器为2时输出高电平,否则输出低电平。之后每次时钟上升沿切换一次状态并更新计数器,当从状态B切换至状态C时,计数器变为当前输入w(即高电平记一次数)。
代码如下:
module top_module (
input clk,
input reset, // Synchronous reset
input s,
input w,
output z
);
parameter A=2'b00,B=2'b01,C=2'b10,D=2'b11;
reg [1:0] state,next,count;
always@(*)
begin
case(state)
A:next = s ? B : A;
B:next = C;
C:next = D;
D:next = B;
endcase
end
always@(posedge clk)
begin
if(reset)
state = A;
else
begin
if(state == A)
count = 2'b0;
else if(state == B)
count = w;
else
count = count + w;
state = next;
end
end
always@(*)
begin
z = (state == B && count == 2);
end
endmodule
通过作者的仿真,结果输出正确。