Search code examples
initializationverilogquartus

How to initialize an output in verilog?


I have been trying to initialize my output LEDR [3:0] to all 0. However, LEDR keeps being XXXX in my waveform timing diagram. I have tried using initial block, but it doesn't work. (My IDE is Quartus Prime)

Here is my code

module synasyn_counter(SW,LEDR,PLoad,CLK);
    parameter n=16;
    input CLK,PLoad;
    input [3:0] SW;
    output reg [3:0] LEDR;
    initial 
    begin
        LEDR=0;
    end
    always @(negedge PLoad or negedge CLK)
    begin
        if (PLoad==0) LEDR<=SW;
        else 
        begin
            if (LEDR==n-1) LEDR<=0;
            else LEDR<=LEDR+1;
        end
    end
endmodule

And this is my result:

enter image description here


Solution

  • You can not use an initial block in synthesized code. That is meant to be a purely simulation based code.

    In hardware, we generally achieve a flop/register initialization through a reset signal. So if you have an active low asynchronous reset in your design, you can do something like this for your flop equation -

    always @ (posedge clock or negedge reset) begin
      if(!reset) begin
        LEDR <= <initialized_value>
      end
      else begin
        <rest_of_your_code>
      end
    end
    

    After you have done this, in your TB ensure that at the start you are asserting the reset signal (since its active low asserting would mean to pull it down to 0) and then de-asserting it after 1 or more clock cycles.

    Please note that, before the reset is asserted you will still see an X unless the reset is asserted from t=0. So after you follow one reset assertion-deassertion sequence, you can proceed with the rest of your simulations after that