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

T Flip Flop

Verilog Flip Flops

T Flip Flop — a ready-to-run Verilog example.

Open in IDE
design.v
module tff ( 	input clk,
            	input rstn,
            	input t,
            output reg q);
  
  always @ (posedge clk) begin
    if (!rstn) 
      q <= 0;
    else
    	if (t)
      		q <= ~q;
    	else
      		q <= q;
  end
endmodule
testbench.v
module tb;
  reg clk;
  reg rstn;
  reg t;
  
  tff u0 (	.clk(clk),
          	.rstn(rstn),
          	.t(t),
          .q(q));
  
  always #5 clk = ~clk;
  
  initial begin  
    {rstn, clk, t} <= 0;
    
    $monitor ("T=%0t rstn=%0b t=%0d q=%0d", $time, rstn, t, q);
    repeat(2) @(posedge clk);
    rstn <= 1;
    
    for (integer i = 0; i < 20; i = i+1) begin
      reg [4:0] dly = $random;
      #(dly) t <= $random;
    end
	#20 $finish;
  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.