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.
直接上代码。
module top_module (
input clk,
input reset, // Synchronous reset
input s,
input w,
output reg z
);
parameter A = 1'h0;
parameter B = 1'h1;
reg cur_state, nxt_state;
reg [1:0] clk_cnt, w_p_cnt;
always @(*)
begin
case(cur_state)
A:
begin
nxt_state = s?B:A;
end
B:
begin
nxt_state = B;
end
default:
begin
nxt_state = A;
end
endcase
end
always @(posedge clk)
begin
if(reset)
cur_state <= A;
else
cur_state <= nxt_state;
end
always @(posedge clk)
begin
if(reset)
z <= 1'h0;
else
begin
case(cur_state)
A:
begin
z <= 1'h0;
end
B:
begin
z <= clk_cnt == 2'h2 && ((w_p_cnt == 2'h2 && !w) || (w_p_cnt == 1'h1 && w));
end
default:
begin
z <= 1'h0;
end
endcase
end
end
always @(posedge clk)
begin
if(reset)
clk_cnt <= 1'h0;
else if(cur_state == A)
clk_cnt <= 1'h0;
else if(clk_cnt == 2'h2)
clk_cnt <= 1'h0;
else
clk_cnt <= clk_cnt + 1'h1;
end
always @(posedge clk)
begin
if(reset)
w_p_cnt <= 1'h0;
else if(cur_state == A)
w_p_cnt <= 1'h0;
else if(clk_cnt == 2'h2)
w_p_cnt <= 1'h0;
else if(w)
w_p_cnt <= w_p_cnt + 1'h1;
else
w_p_cnt <= w_p_cnt;
end
endmodule