-- FDIV.vhd
-- ---------------------------------------
--    Freq Divider for Ex3
-- ---------------------------------------
-- (c) ALSE
-- http://www.alse-fr.com
--

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;

-- ---------------------------------------
ENTITY FDIV IS
    -- ---------------------------------------
    GENERIC (Fclock : POSITIVE := 60E6); -- System Clock Freq in Hertz
    PORT (
        CLK : IN STD_LOGIC;
        RST : IN STD_LOGIC;
        Tick10us : OUT STD_LOGIC;
        Tick1ms : OUT STD_LOGIC;
        Tick10ms : OUT STD_LOGIC);
END FDIV;

-- ---------------------------------------
ARCHITECTURE RTL OF FDIV IS
    -- ---------------------------------------

    CONSTANT Divisor : POSITIVE := Fclock / 1E5; -- we want 100 kHz ticks
    SIGNAL Count : INTEGER RANGE 0 TO Divisor - 1;
    SIGNAL Count2 : INTEGER RANGE 0 TO 99;
    SIGNAL Count3 : INTEGER RANGE 0 TO 9;
    SIGNAL Tick10us_i : STD_LOGIC;
    SIGNAL Tick1ms_i : STD_LOGIC;
    SIGNAL Tick10ms_i : STD_LOGIC;

    --------
BEGIN
    --------
    Tick10us <= Tick10us_i;
    Tick1ms <= Tick1ms_i;
    Tick10ms <= Tick10ms_i;

    PROCESS (RST, CLK)
    BEGIN
        IF RST = '1' THEN
            Count <= 0;
            Count2 <= 0;
            Count3 <= 0;
            Tick10us_i <= '0';
            Tick1ms_i <= '0';
            Tick10ms_i <= '0';

        ELSIF rising_edge (CLK) THEN

            Tick10us_i <= '0';
            Tick1ms_i <= '0';
            Tick10ms_i <= '0';

            IF Count < Divisor - 1 THEN
                Count <= Count + 1;
            ELSE
                Count <= 0;
                Tick10us_i <= '1';
            END IF;

            IF Tick10us_i = '1' THEN
                IF Count2 < 99 THEN
                    Count2 <= Count2 + 1;
                ELSE
                    Count2 <= 0;
                    Tick1ms_i <= '1';
                END IF;
            END IF;

            IF Tick1ms_i = '1' THEN
                IF Count3 < 9 THEN
                    Count3 <= Count3 + 1;
                ELSE
                    Count3 <= 0;
                    Tick10ms_i <= '1';
                END IF;
            END IF;

        END IF;
    END PROCESS;

END RTL;