Verilog Code for Frequency Divider by 2: Simple Example
A frequency divider by 2 in Verilog can be created using a flip-flop that toggles its output on every clock edge. Use a
reg to store the output and toggle it inside an always @(posedge clk) block to halve the input clock frequency.Syntax
The basic syntax for a frequency divider by 2 uses a reg variable to hold the output signal. Inside an always @(posedge clk) block, the output toggles its value on every rising edge of the input clock.
reg q;: stores the divided clock output.always @(posedge clk): triggers on the rising edge of the input clock.q <= ~q;: toggles the output to divide frequency by 2.
verilog
module freq_div2(
input wire clk,
output reg q
);
initial q = 0; // Initialize output to 0
always @(posedge clk) begin
q <= ~q;
end
endmoduleExample
This example shows a complete Verilog module that divides the input clock frequency by 2. The output q toggles on every rising edge of clk, effectively halving the frequency.
verilog
module freq_div2(
input wire clk,
output reg q
);
initial q = 0; // Initialize output to 0
always @(posedge clk) begin
q <= ~q; // Toggle output on each clock rising edge
end
endmoduleOutput
If input clock frequency is 100 MHz, output q frequency will be 50 MHz (a square wave toggling every 10 ns).
Common Pitfalls
Common mistakes when creating a frequency divider by 2 include:
- Not initializing the output
reg, which can cause simulation mismatches. - Using blocking assignments (
=) instead of non-blocking (<=) inside thealwaysblock, leading to incorrect toggling behavior. - Triggering on the wrong clock edge or using asynchronous logic, which can cause glitches.
verilog
/* Wrong way: Using blocking assignment */ module wrong_div2( input wire clk, output reg q ); initial q = 0; always @(posedge clk) begin q = ~q; // Blocking assignment causes timing issues end endmodule /* Right way: Using non-blocking assignment */ module correct_div2( input wire clk, output reg q ); initial q = 0; always @(posedge clk) begin q <= ~q; // Correct toggling end endmodule
Quick Reference
| Concept | Description |
|---|---|
| clk | Input clock signal to be divided |
| q | Output signal toggling at half the input clock frequency |
| always @(posedge clk) | Block triggered on rising edge of clk |
| q <= ~q; | Toggle output to divide frequency by 2 |
| initial q = 0; | Initialize output to known state |
Key Takeaways
Use a flip-flop style toggle inside an always block triggered by the clock's rising edge to divide frequency by 2.
Always use non-blocking assignments (<=) inside sequential always blocks for correct behavior.
Initialize output registers to avoid simulation mismatches.
Avoid asynchronous or combinational logic for frequency division to prevent glitches.
The output frequency is exactly half the input clock frequency with this simple toggle method.