Skip to content
systemcoding.dev
Hardware

Write a flip-flop with synchronous reset in Verilog

Put the reset test inside the clocked always block, before the enable, so Verilog-2005 synthesises a D flip-flop with synchronous reset and clock enable.

1 min read
Summarize in AI

A synchronous reset is only looked at on a clock edge, so it belongs inside the clocked block, not in the sensitivity list. Writing the reset test first also gives it priority over the enable.

dff_sr.vverilog
module dff_sr (
    input  wire clk,
    input  wire rst,
    input  wire en,
    input  wire d,
    output reg  q
);
    always @(posedge clk) begin
        if (rst)
            q <= 1'b0;
        else if (en)
            q <= d;
    end
endmodule

With rst high and en low, q still clears at the next edge, because the if (rst) branch is checked before en. Reverse the order and a disabled flip-flop would ignore reset, which surprises people when a block is gated off during start-up.

The reason to write it this way is the hardware. The iCE40 logic cell has a flip-flop variant with clock enable and synchronous reset (SB_DFFESR in the iCE Technology Library), so Yosys 0.46 maps this block to a single cell with no extra LUT. An asynchronous reset needs always @(posedge clk or posedge rst) and a different cell, and an async reset that releases close to a clock edge can violate recovery time.

If the reset arrives from outside the FPGA, pass it through a two-flop synchroniser first.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.