What is Always Block in Verilog: Explanation and Examples
always block is a fundamental construct used to describe behavior that should run repeatedly whenever specified signals change. It acts like a continuous watcher that triggers its code whenever the signals in its sensitivity list update, allowing you to model hardware logic such as flip-flops or combinational circuits.How It Works
Think of an always block as a little robot that waits for certain signals to change, then quickly runs the instructions inside it. This robot keeps watching those signals forever, so every time one changes, it reacts immediately.
Inside the always block, you write code that describes how your hardware should behave when those signals change. For example, if you want to update a value when a clock signal ticks, you put that logic inside an always block sensitive to the clock.
This mechanism helps you model real hardware behavior where circuits respond to changes in inputs or clocks continuously.
Example
This example shows a simple flip-flop that stores a bit when the clock rises.
module flip_flop(
input wire clk,
input wire d,
output reg q
);
always @(posedge clk) begin
q <= d;
end
endmoduleWhen to Use
Use an always block whenever you want to describe hardware behavior that depends on changes in signals, such as clocks or inputs. It is essential for modeling sequential logic like flip-flops, counters, and state machines.
For combinational logic that depends on inputs, you can also use always blocks sensitive to all input changes. This makes your design react immediately to input changes, just like real circuits.
In real-world designs, always blocks help you build the core logic that runs continuously and updates outputs based on inputs and clocks.
Key Points
- An
alwaysblock runs its code repeatedly whenever signals in its sensitivity list change. - It models hardware behavior that reacts to signal changes, like flip-flops or combinational logic.
- Use
posedgeornegedgein sensitivity lists to trigger on clock edges. - Inside
always, use non-blocking assignments (<=) for sequential logic. - It is a core building block for describing hardware in Verilog.