-- -----------------------------------------------------------
-- 
-- Additional material to the book
-- Modeling and Simulation for RF System Design
-- 
--
-- THIS MODEL IS LICENSED TO YOU "AS IT IS" AND WITH NO WARRANTIES, 
-- EXPRESSED OR IMPLIED. THE AUTHORS SPECIFICALLY DISCLAIM ALL IMPLIED 
-- WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
-- THEY MUST NOT HAVE ANY RESPONSIBILITY FOR ANY DAMAGES, FINANCIAL OR
-- LEGAL CLAIMS WHATEVER.
-- -----------------------------------------------------------

-- Name:      Analog-to-digital converter
-- 
-- Description:
-- This model describes an analog to digital converter. The conversion
-- is done by successive approximation in a digital process at every
-- rising clock edge.
--
-- Literature:
-- 
-- Dependencies: 
-- -----------------------------------------------------------
-- Logical Library         Design unit
-- -----------------------------------------------------------
-- IEEE_proposed           ELECTRICAL_SYSTEMS
-- IEEE                    MATH_REAL
-- -----------------------------------------------------------
--
-- Source:
-- a2d.vhd
-- -----------------------------------------------------------

library IEEE, IEEE_proposed;                                            
  use IEEE_proposed.ELECTRICAL_SYSTEMS.all;
  use IEEE.MATH_REAL.all;

entity A2D is
  generic (PMAX_DBM   : REAL := -100.0;   -- maximum power amplitude [dBm]
	   RIN        : REAL := 50.0      -- input resistance [Ohm], MIN: >0.0
	   );
  port (terminal A   : ELECTRICAL;        -- analog input
	terminal GND : ELECTRICAL;        -- analog ground
        signal   D   : out BIT_VECTOR;    -- digital output
        signal   CLK : in BIT             -- clock input
	);
begin
  assert RIN > 0.0
    report "rin must be > 0.0"
    severity error;
end entity A2D;

architecture BHV_RF of A2D is
  constant PA         : REAL    := 10**((PMAX_DBM-30.0)/10.0); 
  constant VA         : REAL    := SQRT(PA * 2.0 * RIN);
  constant MAX_NUMBER : INTEGER := 2**D'LENGTH-1;
  constant VSB        : REAL    := VA/(2.0**D'LENGTH-1.0);
  quantity VIN across IIN through A to GND;

begin

  -- input impedance
  VIN == RIN * IIN;
  
  -- conversion process
  process (CLK) is
    variable NUMBER  : INTEGER;
    begin
      if CLK'EVENT and CLK = '1' then
        NUMBER := INTEGER(TRUNC((VIN + VSB/2.0)/VSB));
        if NUMBER < 0 then
          NUMBER := 0;
        elsif NUMBER > MAX_NUMBER then
          NUMBER := MAX_NUMBER;
        end if;

        for I in D'LOW to D'HIGH loop
          if NUMBER mod 2 = 1 then
            D(I) <= '1';
          else
            D(I) <= '0';
          end if;
          NUMBER := NUMBER/2;
        end loop;
      end if;
  end process;

end architecture BHV_RF;
