VHDL Clock Divider – Design and Implementation Guide

vhdl

I dont really understand the below code, for rising edge of the clock a divider of 4 bits will be incremented, so:
0000 -> 0001 -> 0010 -> 0011
For each rising edge of the clock?

What is div(2)?

enter image description here

Best Answer

If you run a simple simulation (which you will need to learn how to do if you're going to be working with VHDL) you'll see that div only updates on the rising edge of the clock. This means that div(0) is 1/2 the clock rate, div(1) is 1/4 the clock rate, and div(2) is 1/8 the clock rate.

Simulation

Normally, I'm not in the habit of posting code, but the testbench for simulating this is so trivial I might as well. Note: I've replaced the std_logic_vector type on cnt and div with an unsigned type since addition of std_logic_vectors uses non-standard libraries (or VHDL2008).

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity clk_div is
end clk_div;

architecture TB of clk_div is
signal clk      :   std_logic; -- 200MHz clk
signal cnt      :   unsigned(2 downto 0) := (others => '0');
signal div      :   unsigned(3 downto 0) := (others => '0');

begin

--create 200MHz clock
process
begin
    clk <= '1'; wait for 2.5 ns;
    clk <= '0'; wait for 2.5 ns;
end process;

process(clk)
begin
    if rising_edge(clk) then
        div <= div + 1;
    end if;
end process;

process(div(2))
begin
    if rising_edge(div(2)) then
        cnt <= cnt + 1;
    end if;
end process;

end TB;