Search code examples
verilogmodelsim

How to initialize a wire with constant in verilog ?


In the below mentioned verilog code for J-K Flip Flop , i want to initialize wire type q and q_bar with some value. For eg : I am initializing here q and q_bar with 0. But in the output, q and q_bar has don't care (1'hx) value . So how to initialize wire type with constant ?

module JK_FF(j,k,clk,q,q_bar) ;
input j,k,clk ;
output q , q_bar  ;
wire s,r,w,z ;

assign w = q ;
assign z = q_bar ;

nand U1(s,j,clk,z) ;
nand U2(r,k,clk,w) ;
nand U3(q,s,z) ;
nand U4(q_bar,r,w) ;

endmodule

/*  TEST BENCH  */

module JK_FF_TB ;

reg j,k,clk ;
wire q , q_bar ;

assign q = 1'b0 ;
assign q_bar = 1'b0 ;

initial begin
clk = 1'b1 ;
end 

JK_FF DUT(j,k,clk,q,q_bar) ;

 initial
 begin
 j = 1'b0 ;
 k = 1'b0 ;

 #5

  j = 1'b0 ;
  k = 1'b1 ;

  #5

  j = 1'b1 ;
  k = 1'b0 ;

  #5

  j = 1'b1 ;
  k = 1'b1 ;

  end
  endmodule 

Solution

  • There are several issues to address.

    State in Verilog, like flip-flop value, is usually kept in reg type, where the value can be initialized using initial. However, in the simple flip-flop made of gates there are only wires, which can't be initialized.

    The design with the crossed NAND gates will in an hardware implementation lead to a stable value at start up, even when the wires are initially undefined 1'bX. You can emulate this in the circuit using conversion from 1'X to 1'b0 or 1'b1 at q and q_bar using assign as:

    assign w = q !== 1'b0;  // 1'bX => 1
    assign z = q_bar === 1'b1;  // 1'bX => 0
    

    The Verilog implementation will however give a race condition, since the clock pulse will always be too long for the immediate change that occur if this design is simulated. This is typically shown as an infinite iteration during simulation, thereby reaching iteration limits with resulting error.

    So more modifications are required, and you can find a great tutorial here: The JK Flip Flop