--=====================================================
-- Проект 10. Широтно-импульсный модулятор
-- Счётчик периода сравнивается с заданной скважностью.
-- Разрядность задаётся параметром generic.
--=====================================================
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity pwm is
    generic (
        WIDTH : integer := 8                            -- разрядность ШИМ
    );
    port (
        clk     : in  std_logic;
        rst     : in  std_logic;
        duty    : in  std_logic_vector(WIDTH-1 downto 0);   -- скважность
        pwm_out : out std_logic
    );
end entity pwm;

architecture rtl of pwm is
    signal cnt : unsigned(WIDTH-1 downto 0) := (others => '0');
begin
    process (clk, rst)
    begin
        if rst = '1' then
            cnt <= (others => '0');
        elsif rising_edge(clk) then
            cnt <= cnt + 1;                             -- свободно бегущий счётчик
        end if;
    end process;

    -- выход активен, пока счётчик меньше значения скважности
    pwm_out <= '1' when cnt < unsigned(duty) else '0';
end architecture rtl;
