I wrote a program for a '11' sequence detector to be implemented by both Moore and Mealy machine. The problem statement is for z to be asserted high after x has been high for 2 cycles. I've attached my implementation below, but what I am seeing is that for both FSMs, z is asserted one cycle too early. Can anyone spot the error in my FSM or code? I would really appreciate any input on what I may be doing wrong! Thanks
FSM:
Systemverilog code:
Moore:
module moore_fsm
(input bit clk, reset, x,
output bit z);
typedef enum bit [1:0] {A, B, C} states;
states current_state, next_state;
always_ff @(posedge clk, negedge reset) begin
if (~reset)
current_state <= A;
else current_state <= next_state;
end
always_comb begin
case (current_state)
A:begin
z=0;
if (x==0) begin
next_state = A;
end
else begin
next_state = B;
end
end
B: begin
z=0;
if (x==1) begin
next_state = C;
end
else begin
next_state = A;
end
end
C: begin
z=1;
if (x==1) begin
next_state = C;
end
else begin
next_state = A;
end
end
endcase
end
endmodule:moore_fsm
Mealy:
module mealy_fsm
(input bit clk, reset, x,
output bit z);
typedef enum bit {A, B} states;
states current_state, next_state;
always_ff @(posedge clk, negedge reset) begin
if (~reset)
current_state <= A;
else current_state <= next_state;
end
always_comb
begin
case (current_state)
A: if (x==1) begin
next_state = B;
z=0;
end
else begin
next_state = A;
z=0;
end
B: if (x==1) begin
next_state = B;
z=1;
end
else begin
next_state = A;
z=0;
end
endcase
end
endmodule:mealy_fsm
Testbench
module moore_mealy ();
bit clk, reset, x, moore_z, mealy_z;
moore_fsm dut1 (clk, reset, x, moore_z);
mealy_fsm dut2 (clk, reset, x, mealy_z);
initial begin
reset = 1;
#1 reset = 0;
#1 reset = 1;
#5 x=0;
#5 x=1;
#28 x=0;
#20 x=1;
#10 x=0;
#10 x=1;
#150 $finish;
end
always begin
#5 clk = ~clk;
end
endmodule:moore_mealy
Output Waveform:
Best Answer
In your Moore machine you set the 'z' in the combinatorial section. At the same time as you set the state to C. Thus the two coincide. To get z high after two bits have been detected (thus after the state C) you must move the assignment into the clocked section:
Your Mealy machine is a problem. The definition of Mealy brings with it that the input defines the output directly. Thus Mealy dictates that you must use a combinatorial statement of the type:
assign z = some_condition_with_state && x; // or without assign in your always_comb section
The 'directly' means you can't really set 'z' after x has been high for two clocks as by that time it may have gone low again.
One last tip: Don't use variables like 'z' and 'x' as they are too easily confused with 1'bx and 1'bz.