--=====================================================
-- Проект 43. Генератор CRC-8
-- Последовательно принимает биты и вычисляет
-- контрольную сумму по образующему полиному.
--=====================================================
library ieee;
use ieee.std_logic_1164.all;

entity crc8 is
    generic (
        POLY : std_logic_vector(7 downto 0) := x"07"     -- полином CRC-8-CCITT
    );
    port (
        clk      : in  std_logic;
        rst      : in  std_logic;
        data_in  : in  std_logic;                         -- входной бит
        bit_valid: in  std_logic;                          -- строб приёма бита
        crc_out  : out std_logic_vector(7 downto 0)
    );
end entity crc8;

architecture rtl of crc8 is
    signal crc : std_logic_vector(7 downto 0) := (others => '0');
begin
    process (clk, rst)
        variable fb : std_logic;
    begin
        if rst = '1' then
            crc <= (others => '0');
        elsif rising_edge(clk) then
            if bit_valid = '1' then
                fb  := crc(7) xor data_in;                -- бит обратной связи
                crc <= crc(6 downto 0) & '0';
                if fb = '1' then
                    crc <= (crc(6 downto 0) & '0') xor POLY;
                end if;
            end if;
        end if;
    end process;

    crc_out <= crc;
end architecture rtl;
