-- --------------
-- LED Blinker 
-- --------------
-- Lucas GRELAUD

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

ENTITY LED_BLINKER IS
    PORT (
        CLK : IN STD_LOGIC;
        RESET_N : IN STD_LOGIC; -- Inversed logic => 0v = true, 3.3v = false

        LED_STATE : OUT STD_LOGIC
    );
END ENTITY LED_BLINKER;

ARCHITECTURE RTL OF LED_BLINKER IS
    -- ---------------------------------
    -- Signal declaration
    -- ---------------------------------
    SIGNAL RST_N : STD_LOGIC;
    SIGNAL RST : STD_LOGIC;

    SIGNAL Tick10us : STD_LOGIC;
    SIGNAL Tick1ms : STD_LOGIC;
    SIGNAL Tick10ms : STD_LOGIC;

BEGIN
    -- --------------------------------
    -- External Reset resynchronization
    -- --------------------------------
    PROCESS (CLK)
    BEGIN
        IF rising_edge (CLK) THEN
            RST_N <= RESET_N;
            RST <= NOT RST_N;
            LED_STATE <= '0';
        END IF;
    END PROCESS;

    -- ---------------------------------
    -- Frequency Divider instanciation
    -- ---------------------------------
    i_fdiv : ENTITY work.fdiv
        GENERIC MAP(FCLOCK => 50E6) -- 50 MHz
        PORT MAP(
            CLK => CLK,
            RST => RST,
            Tick10us => Tick10us,
            Tick1ms => Tick1ms,
            Tick10ms => Tick10ms);

    -- ---------------------------------
    -- LED Blink process
    -- ---------------------------------
    PROCESS (CLK, RST)
        VARIABLE current_state : STD_LOGIC;
    BEGIN
        IF RST = '1' THEN
            LED_STATE <= '0';
            current_state := '0';
        ELSIF rising_edge (CLK) THEN
            IF Tick1ms = '1' THEN
                current_state := NOT current_state;
                LED_STATE <= current_state;
            END IF;
        END IF;
    END PROCESS;
END ARCHITECTURE RTL;