0
0
VerilogHow-ToBeginner · 3 min read

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

endmodule
💻

Example

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

endmodule
Output
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 the always block, 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

ConceptDescription
clkInput clock signal to be divided
qOutput 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.