0
0
Verilogprogramming~5 mins

D flip-flop with clock edge in Verilog

Choose your learning style9 modes available
Introduction

A D flip-flop stores a single bit of data and changes its output only at the clock's edge. This helps keep data stable and synchronized in digital circuits.

To store a bit of information that updates only when a clock signal changes.
When building memory elements like registers in a digital system.
To synchronize signals between different parts of a circuit.
When you want to avoid glitches by updating data only on clock edges.
Syntax
Verilog
module d_flip_flop(
    input wire clk,
    input wire d,
    output reg q
);

always @(posedge clk) begin
    q <= d;
end

endmodule

posedge clk means the code runs when the clock signal changes from 0 to 1 (rising edge).

The q <= d; line updates the output q with the input d at the clock edge.

Examples
Updates output q on the rising edge of the clock.
Verilog
always @(posedge clk) begin
    q <= d;
end
Updates output q on the falling edge of the clock (when clock goes from 1 to 0).
Verilog
always @(negedge clk) begin
    q <= d;
end
A D flip-flop with asynchronous reset that clears output q when rst is high.
Verilog
module dff_async_reset(
    input wire clk,
    input wire rst,
    input wire d,
    output reg q
);

always @(posedge clk or posedge rst) begin
    if (rst)
        q <= 0;
    else
        q <= d;
end

endmodule
Sample Program

This testbench creates a clock signal and changes the input d. The output q updates only on the rising edge of the clock, showing how the D flip-flop stores data.

Verilog
module testbench;
    reg clk = 0;
    reg d = 0;
    wire q;

    d_flip_flop uut (
        .clk(clk),
        .d(d),
        .q(q)
    );

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

    initial begin
        $monitor($time, ": clk=%b d=%b q=%b", clk, d, q);

        d = 0; #10;
        d = 1; #10;
        d = 0; #10;
        d = 1; #10;
        $finish;
    end
endmodule

module d_flip_flop(
    input wire clk,
    input wire d,
    output reg q
);

always @(posedge clk) begin
    q <= d;
end

endmodule
OutputSuccess
Important Notes

The output q changes only at the clock's rising edge, not immediately when d changes.

Using non-blocking assignment <= inside always block is important for correct timing behavior.

Initial value of q is unknown (shown as 'x') until the first clock edge.

Summary

A D flip-flop stores data on the clock's rising edge.

Use always @(posedge clk) to trigger updates.

It helps keep digital circuits synchronized and stable.