0
0
Verilogprogramming~5 mins

T flip-flop behavior in Verilog

Choose your learning style9 modes available
Introduction

A T flip-flop changes its output only when the input T is 1 and a clock pulse happens. It helps store and toggle bits in digital circuits.

To build counters that count up or down in digital electronics.
When you want to toggle a signal on each clock pulse.
To divide the frequency of a clock signal by 2.
In memory elements that need to change state conditionally.
Syntax
Verilog
always @(posedge clk or posedge reset) begin
  if (reset)
    q <= 0;
  else if (t)
    q <= ~q;
end

posedge clk means the code runs on the rising edge of the clock.

reset sets the output to 0 immediately.

Examples
Basic T flip-flop without reset. Output toggles when T is 1 on clock edge.
Verilog
always @(posedge clk) begin
  if (t)
    q <= ~q;
end
T flip-flop with asynchronous reset to clear output.
Verilog
always @(posedge clk or posedge reset) begin
  if (reset)
    q <= 0;
  else if (t)
    q <= ~q;
end
Sample Program

This program defines a T flip-flop with reset. The testbench toggles clock every 5 units, applies reset, and changes T input to show how output Q toggles only when T is 1 on clock rising edge.

Verilog
module t_flip_flop(
  input wire clk,
  input wire reset,
  input wire t,
  output reg q
);

always @(posedge clk or posedge reset) begin
  if (reset)
    q <= 0;
  else if (t)
    q <= ~q;
end

endmodule

// Testbench
module test;
  reg clk = 0;
  reg reset = 0;
  reg t = 0;
  wire q;

  t_flip_flop uut(.clk(clk), .reset(reset), .t(t), .q(q));

  always #5 clk = ~clk; // Clock toggles every 5 time units

  initial begin
    $monitor($time, ": reset=%b t=%b q=%b", reset, t, q);
    reset = 1; #10;
    reset = 0; t = 1; #10;
    t = 0; #20;
    t = 1; #20;
    $finish;
  end
endmodule
OutputSuccess
Important Notes

The output Q only toggles when T is 1 at the clock's rising edge.

Reset is asynchronous, so it sets Q to 0 immediately when active.

Without reset, the flip-flop keeps its last state if T is 0.

Summary

A T flip-flop toggles output Q when T is 1 on clock rising edge.

Reset clears output to 0 immediately.

Used in counters and frequency dividers.