1
`timescale 1ns/1ps

module div_by_3(
    input clk,
    input rst,
    output y
);

reg [1:0] state, nextstate;

//state encoding
parameter S0 = 2'b00;
parameter S1 = 2'b01;
parameter S2 = 2'b10;

//state registers
always@(posedge clk or negedge rst) begin
    if(rst)     state <= S0;
    else        state <= nextstate;
end

//next state logic
always@(*) 
    case(state) 
        S0  :   nextstate   =   S1;
        S1  :   nextstate   =   S2;
        S2  :   nextstate   =   S0;
        default :   nextstate   =   S0;     
     endcase

//output logic
assign y = (state   == S0);

endmodule

//======================================================================// 
//                            Test Bench
//======================================================================//

`timescale 1ns/1ps

 module div_by_3_tb();
 //=====================================================
 //                 Clock
 //=====================================================

  parameter clk_per = 10;

  reg Clk;

  initial Clk = 1'b0;
  always #(clk_per * 0.5) Clk = ~Clk;

  //=====================================================
  //                    Instances
  //=====================================================

  parameter dly = 2;

  reg       rst ;
  wire      out ;
  reg       out_start   ;

  div_by_3 uut(
      .clk(Clk),
      .rst(rst),
      .y(out)
  );

  //=====================================================
  //                    Inputs
  //=====================================================

  initial begin
    //Initialize inputs
    rst = 1'b1;
    #(dly)  rst = 1'b0;
    out_start   = 1'b0;
    #(clk_per * 20)     out_start = 1'b1;
    $finish;
  end

  //=====================================================
  //                    Verify
  //=====================================================

  initial begin
      wait(out_start==1'b1) begin
          $display("Simulation complete...");
      end
  end

  //=====================================================
  //                    Dump Waves
  //=====================================================

  initial begin
      $dumpfile("div_by_3.vcd");
      $dumpvars;
  end

  endmodule

I am trying to model a simple divide by 3 counter. I am using Icarus Verilog 0.9.7 simulator (online), and upon running the code, I am not able to see any state change (the state remains stuck at X). I am not able to figure out the cause. Is it a problem with the simulation tool, or is the code incorrect?

toolic
  • 57,801
  • 17
  • 75
  • 117

1 Answers1

0

Your code is incorrect. The error is the polarity of rst. One way to fix this is to change:

always@(posedge clk or negedge rst) begin

to:

always@(posedge clk or posedge rst) begin
toolic
  • 57,801
  • 17
  • 75
  • 117