-------------------------------------------------------------
-- MSS copyright 1999-2017
--	Filename:  PWM2.VHD
-- Author: Alain Zarembowitch / MSS
--	Version: 1
--	Date last modified: 3/29/17
-- Inheritance: 	PWM.VHD 5/24/08, COM-1018 AGC2
--
-- Description:  converting a NBITS number into a  
-- to a pulse-width modulated digital output. 
-- Use case: AGC output compatible with the COM-300X receivers
-- Maximum INPUT is for maximum OUTPUT.
-------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity PWM2 is 
generic (
	NBITS: integer
);
port(
	--// GLOBAL CLOCKS
   CLK : in std_logic;				
		-- master clock
		
	INPUT : in  STD_LOGIC_VECTOR (NBITS-1 downto 0);
		-- unsigned format
	INPUT_SAMPLE_CLK: in std_logic;
		-- INPUT is valid at rising edge of CLK when INPUT_SAMPLE_CLK = '1'
	
	
   OUTPUT : out  STD_LOGIC
		-- PWM output
);
end entity;

architecture Behavioral of PWM2 is
------------------------------------------------------
--			COMPONENTS
------------------------------------------------------ 
------------------------------------------------------
--			SIGNALS
------------------------------------------------------    
signal INPUT_D: unsigned(NBITS-1 downto 0);   
signal PWM_COUNT: unsigned(NBITS-1 downto 0);
signal PWM_COUNT2: unsigned(NBITS-1 downto 0);
     --counter for creating the PWM_OUT before increment
	 --unsigned representation	 
------------------------------------------------------
--			IMPLEMENTATION
------------------------------------------------------       
begin

PWM_COUNT_PROC:process (CLK)
begin  
	if rising_edge(CLK) then   
  		PWM_COUNT <= PWM_COUNT + 1;   

		-- reclock input signal
		if(INPUT_SAMPLE_CLK = '1') then
			INPUT_D <= unsigned(INPUT);
		end if;
	end if;
end process;
    
-- randomize the pulse width modulated signal
RANDOM_GEN: process(PWM_COUNT)
begin
	for I in 0 to NBITS-1 loop
		PWM_COUNT2(I) <= PWM_COUNT(NBITS-1-I);
	end loop;
end process;


PWM_OUT_PROC: process (CLK)
begin
	if rising_edge(CLK) then   
		if (PWM_COUNT2 < INPUT_D) then
			 --Threshold for determining when PWM turns from 1 to 0.
			 --Changes Counter_O from signed to unsigned magnitude
			OUTPUT <= '1'; 
		else
			OUTPUT <= '0';   
		end if; 
	end if;
end process;

end Behavioral;

