0
0
VhdlHow-ToBeginner · 3 min read

VHDL Code for Clock Divider by 2: Simple Example and Explanation

A clock divider by 2 in VHDL can be created by toggling a flip-flop on every rising edge of the input clock using process and if rising_edge(clk). This divides the input clock frequency by 2 by outputting a signal that changes state every two clock cycles.
📐

Syntax

The basic syntax for a clock divider by 2 uses a process block triggered on the rising edge of the clock. Inside, a signal is toggled to create the divided clock output.

  • process(clk): Defines a block sensitive to the clock signal.
  • if rising_edge(clk) then: Checks for the clock's rising edge.
  • div_clk <= not div_clk;: Toggles the output signal to divide frequency by 2.
vhdl
process(clk) is
begin
  if rising_edge(clk) then
    div_clk <= not div_clk;
  end if;
end process;
💻

Example

This example shows a complete VHDL entity and architecture that divides an input clock by 2. The output clk_div2 toggles every rising edge of clk, effectively halving the frequency.

vhdl
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity ClockDividerBy2 is
  Port (
    clk     : in  STD_LOGIC;
    reset_n : in  STD_LOGIC;
    clk_div2: out STD_LOGIC
  );
end ClockDividerBy2;

architecture Behavioral of ClockDividerBy2 is
  signal div_clk : STD_LOGIC := '0';
begin
  process(clk, reset_n)
  begin
    if reset_n = '0' then
      div_clk <= '0';
    elsif rising_edge(clk) then
      div_clk <= not div_clk;
    end if;
  end process;

  clk_div2 <= div_clk;
end Behavioral;
Output
The output signal clk_div2 toggles every two clock cycles, producing a frequency half of the input clk.
⚠️

Common Pitfalls

Common mistakes when writing a clock divider by 2 include:

  • Not using rising_edge(clk) which can cause incorrect toggling.
  • Forgetting to initialize or reset the output signal, leading to unknown startup states.
  • Using combinational logic instead of a clocked process, which won't divide the clock properly.
vhdl
process(clk) is
begin
  -- Wrong: missing rising_edge check
  div_clk <= not div_clk;
end process;

-- Correct way:
process(clk)
begin
  if rising_edge(clk) then
    div_clk <= not div_clk;
  end if;
end process;
📊

Quick Reference

ConceptDescription
process(clk)Defines a block triggered by clock changes
if rising_edge(clk)Detects the clock's rising edge for synchronous logic
div_clk <= not div_clk;Toggles the output to divide frequency by 2
reset_n signalAsynchronous reset to initialize output signal
clk_div2 outputThe divided clock output signal

Key Takeaways

Use a clocked process with rising_edge(clk) to toggle the output signal.
Initialize or reset the output signal to avoid unknown states at startup.
Toggling the output signal every two clock cycles divides the frequency by 2.
Avoid combinational logic for clock division to ensure proper timing.
The output clock frequency is half the input clock frequency.