0
0
VerilogConceptBeginner · 3 min read

What is always_ff in SystemVerilog: Explanation and Example

always_ff is a SystemVerilog procedural block used to describe sequential logic that triggers on clock or reset edges. It ensures the block models flip-flop behavior and helps tools catch coding mistakes by restricting the kinds of statements allowed inside.
⚙️

How It Works

The always_ff block in SystemVerilog is designed to model flip-flops or registers that update their value on specific clock or reset edges. Think of it like a snapshot camera that only takes a picture when the clock ticks or when a reset happens. This block runs only at those moments, making it perfect for describing sequential circuits.

Unlike the older always block, always_ff restricts what you can write inside it to ensure you only describe sequential logic. This helps catch errors early, like accidentally mixing combinational logic inside a flip-flop block. It’s like having a safety guard that keeps your code clean and correct for hardware synthesis.

💻

Example

This example shows a simple flip-flop that updates its output on the rising edge of a clock or resets to zero when reset is active.

systemverilog
module flip_flop_example(input logic clk, input logic rst_n, input logic d, output logic q);
  always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n)
      q <= 0;
    else
      q <= d;
  end
endmodule
🎯

When to Use

Use always_ff whenever you want to describe sequential logic that depends on clock edges or resets, such as registers, counters, or state machines. It is the modern and recommended way to write flip-flops in SystemVerilog because it improves code clarity and helps synthesis tools detect mistakes.

For example, in designing digital circuits like CPUs or communication controllers, always_ff ensures your timing-sensitive logic behaves correctly and is easier to maintain.

Key Points

  • always_ff models sequential logic triggered by clock or reset edges.
  • It restricts code inside to prevent mixing combinational logic.
  • Helps synthesis tools catch errors early.
  • Recommended over legacy always blocks for flip-flops.
  • Improves code readability and hardware correctness.

Key Takeaways

always_ff is used to write clean, edge-triggered sequential logic in SystemVerilog.
It restricts code inside to only support flip-flop style behavior, preventing mistakes.
Use it for registers, counters, and state machines that depend on clock or reset signals.
It helps synthesis tools detect errors and improves code clarity.
It is the modern replacement for older always blocks when describing flip-flops.