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.
我的思路:添加三个状态机以代替对三个周期进行计数,并在状态机跳转时对w=1的次数进行计数。具体状态图如下:
虽然多用了三个状态机,但这种写法网上还没见过,所以分享一下。
module top_module (
input clk,
input reset, // Synchronous reset
input s,
input w,
output z
);
parameter s0=0,s1=1,s2=2,A=3,B=4;
reg [2:0] state,next;
reg [1:0] c;
//状态逻辑变化
always@(*)begin
case(state)
A : next<=s?B:A;
B : begin next<=s0;end
s0 : begin next<=s1;end
s1 : begin next<=s2;end
s2 : begin next<=s0;end
default : next<=A;
endcase
end
//时钟上升沿变化
always@(posedge clk)
if(reset ) state<=A;
else
begin
case(state)
B : begin state<=next;c<=w?1:0;end
s0 :begin state<=next;c<=w?(c+1):c;end
s1 :begin state<=next;c<=w?(c+1):c;end
s2:begin state<=next;c<=w?1:0;end
default : state<=next;
endcase
//state<=next;
end
assign z = (state==s2&&c==2'h2);//进入s2状态且三个周期内计数为2
endmodule