Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting unexpected output for state machine code

module mealy(input x_in,rst_n,clk, output reg y_out);

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

always@(posedge clk,negedge rst_n) begin
    if(!rst_n) p_state <= s0;
    else
    p_state <= n_state;
end

always@(x_in,p_state) begin
    case (p_state)
        s0:
            n_state = x_in ? s2 : s1;
        s1: 
            n_state = x_in ? s2 : s1;
        s2:
            n_state = x_in ? s2 : s1;
    endcase
end

always@(x_in,p_state) begin
    case (p_state)
        s0:
            y_out = 1'b0;
        s1:
            y_out = x_in ? 1'b1 : 1'b0;
        s2:
            y_out = !x_in ? 1'b1 : 1'b0;
    endcase
end

endmodule
module mealy_tb;

reg x_in,rst_n,clk;
wire y_out;

mealy dut(x_in,rst_n,clk,y_out);

initial begin
    clk = 1'b0;
    forever #10 clk = ~clk;
end

initial begin
    rst_n = 1'b0;
    
    repeat(1000) begin
        x_in = {$random};
        rst_n = 1'b1;
        #10;
    end
    
end

endmodule

The state diagram is given below:
State Diagram

I am getting don’t-care output. Also I am not able to view the state diagram in the state diagram viewer. I have specified the behaviour and output for each state. I am not able to find the error in the code. I need some guidance on writing code for state machines and also the reason why this code does not work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You did not reset your design properly. Add a delay after setting rst_n to 0:

initial begin
    rst_n = 1'b0;
    #20;
    repeat(1000) begin
        x_in = {$random};
        rst_n = 1'b1;
        #10;
    end
    
end

The problem was easy to identify by viewing waveforms of your simulation. rst_n was always 1, which meant that p_state was always x (unknown).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading