Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

D Latch

Verilog Flops & Latches

Example of a D Latch

Open in IDE
Related tutorial:
design.v
module d_latch (  input d,           // 1-bit input pin for data
                  input en,          // 1-bit input pin for enabling the latch
                  input rstn,        // 1-bit input pin for active-low reset
                  output reg q);     // 1-bit output pin for data output
 
   // This always block is "always" triggered whenever en/rstn/d changes
   // If reset is asserted then output will be zero
   // Else as long as enable is high, output q follows input d
   always @ (en or rstn or d)
      if (!rstn)
         q <= 0;
      else
         if (en)
            q <= d;
endmodule
testbench.v
module tb_latch;
   // Declare variables that can be used to drive values to the design
   reg d;  
   reg en;
   reg rstn;
   reg [2:0] delay;
   reg [1:0] delay2;
   integer i;
   
   // Instantiate design and connect design ports with TB signals
   d_latch  dl0 ( .d (d),
                  .en (en),
                  .rstn (rstn),
                  .q (q));

   // This initial block forms the stimulus to test the design
   initial begin
     $monitor ("[%0t] en=%0b d=%0b q=%0b", $time, en, d, q);
     
      // 1. Initialize testbench variables
      d <= 0;
      en <= 0;
      rstn <= 0;
      
      // 2. Release reset
      #10 rstn <= 1;
      
      // 3. Randomly change d and enable
     for (i = 0; i < 5; i=i+1) begin
         delay = $random;
         delay2 = $random;
         #(delay2) en <= ~en;
         #(delay) d <= i;
      end
   end
  
   initial begin
     $dumpvars;
     $dumpfile("dump.vcd");
   end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.