# sequence detector doesn't work expected

I am trying to write verilog code to do sequence detector the the state diagram below. Input is a 2-bit signals and there're 3 state variables as in the image. The goal is to detect the sequence (01)-(11). When this sequence is detected the output (1 bit signal) is 1.

I tried the code below but somehow it doesn't work expected. In my first test, if I set up reset is zero all the time then the output signal some part is correct and some part isn't.

However, when I set a reset at the rising edge of clock, the output is always zero and two registers state and next_state is always unknown. Could anyone tell me what is wrong with it and how to fix it?

module SeqDect(rst,clk,ip,op);

output reg op;
input clk, rst;
input [1:0] ip;
reg [1:0] state;
reg [1:0] next_state;

parameter [1:0] s0=2'b00;
parameter [1:0] s1=2'b01;
parameter [1:0] s2=2'b10;

always @(posedge clk, posedge rst)
begin
if (rst)
state=s0;
else
state=next_state;
end

always @(state, next_state)
begin
case(state)
s0:
if (ip==2'b01)
begin
next_state=s1;
op=1'b0;
end
else
begin
next_state=s0;
op=1'b0;
end

s1:
if (ip==2'b11)
begin
next_state=s2;
op=1'b1;
end
else if (ip==2'b01)
begin
next_state=s1;
op=1'b0;
end
else
begin
next_state=s0;
op=1'b0;
end

s2:
if (ip==2'b11)
begin
next_state=s2;
op=1'b1;
end
else if (ip==2'b01)
begin
next_state=s1;
op=1'b0;
end
else
begin
next_state=s0;
op=1'b0;
end

default:
begin
next_state=s0;
op=1'b0;
end
endcase
end
endmodule

• You should be using non-blocking assignments to update state. Beyond that, if you have a working simulation you can examine internal signals to see where things go wrong. That's much better than trying to debug code by inspection. – Elliot Alderson Apr 15 '19 at 19:41
• @ElliotAlderson I fixed it but the result is same. It doesn't change anything. The problem is still that state and next_state variable are always unknown as in the images. – anhnha Apr 16 '19 at 6:36

your first always block is a sequential circuit so, never forget to use non-blocking assignment.

your second always block is a combinational circuit and you must declare all the input signals in the sensitivity list. or you can set always @(*)

(Line 16,18,21 changed)

    module SeqDect(rst,clk,ip,op);

/*io and internal wires*/

always @(posedge clk, posedge rst)
begin
if (rst)
state<=s0;
else
state<=next_state;
end

always @(state, ip)
begin
case(state)
/*cases*/
endcase
end
endmodule


testbench module:

module tb();

reg rst;
reg clk;
reg [1:0] ip;
wire op;

SeqDect uut(rst,clk,ip,op);

always #20 clk =~clk;

initial begin
clk=0;
rst=1;
#100
rst=0;
#100
ip = 2'b00;
#100
ip = 2'b01;
#100
ip = 2'b11;
#100
\$stop;
end
endmodule


modelsim simulation results: