--=====================================================
-- Проект 13. Синхронизатор тактовых доменов
-- Внешний асинхронный сигнал заводится в схему
-- через цепочку триггеров — иначе возможен сбой.
--=====================================================
library ieee;
use ieee.std_logic_1164.all;

entity synchronizer is
    generic (
        STAGES : integer := 2                           -- число ступеней
    );
    port (
        clk      : in  std_logic;
        rst      : in  std_logic;
        async_in : in  std_logic;                       -- асинхронный вход
        sync_out : out std_logic                        -- сигнал в домене clk
    );
end entity synchronizer;

architecture rtl of synchronizer is
    signal chain : std_logic_vector(STAGES-1 downto 0) := (others => '0');
begin
    process (clk, rst)
    begin
        if rst = '1' then
            chain <= (others => '0');
        elsif rising_edge(clk) then
            -- сдвигаем сигнал по цепочке триггеров
            chain <= chain(STAGES-2 downto 0) & async_in;
        end if;
    end process;

    sync_out <= chain(STAGES-1);
end architecture rtl;
