---------------------------------------------------------------------------
-- NDT Solutions Ltd. Proprietary Information
-- Company Confidential
-- Copyright 2005
--
-- Filename: DacSerial.vhd
-- Language: VHDL '93
-- Project:  Pulse Receive Card Control FPGA
--
-- Design Description:
-- AD5399 DAC serial interface controller
--
---------------------------------------------------------------------------

library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.std_logic_arith.all;

entity DacSerial is
  port(
    pClock   : in  std_ulogic;   -- 33MHz Clock
    pnReset  : in  std_ulogic;
    pDInA    : in  std_logic_vector(11 downto 0);
    pDInAEn  : in  std_ulogic;
    pDinB    : in  std_logic_vector(11 downto 0);
    pDInBEn  : in  std_ulogic;
    pBusy    : out std_ulogic;
    -- DAC signals
    pDAC_nCS : out std_ulogic;
    pDAC_SDI : out std_ulogic;
    pDAC_Clk : out std_ulogic);
end DacSerial;

architecture RTL of DacSerial is

  signal DAC_Clk : std_ulogic;
  signal ShiftReg: std_logic_vector(15 downto 0);
  signal LoadDelayReg: std_logic_vector(15 downto 0);
  signal Busy: Std_logic;
begin
  
  State : process (pClock, pnReset) is
  begin
    if (pnReset ='0') then
      ShiftReg <= (others=> '0');
      LoadDelayReg <= (others => '0');
      pDAC_nCS <= '1';
      DAC_Clk <='1';
      Busy <= '0';
    elsif (pClock'event and pClock = '1') then
      if (Busy = '1') then
        if (DAC_Clk = '1') then
          ShiftReg <= ShiftReg(14 downto 0) & '0';
          LoadDelayReg <= LoadDelayReg(14 downto 0) & '0';
          if (LoadDelayReg(15) = '1') then  -- synchronous with D(0)
            pDAC_nCS <= '1';
            Busy <= '0';
          else
            DAC_Clk <= '0';
          end if;
        else
          DAC_Clk <= '1';
        end if;
      elsif (pDinAEn = '1') then
        ShiftReg <= "0000" & pDInA;
        LoadDelayReg(0) <= '1';
        DAC_Clk <= '0';
        pDAC_nCS <= '0';
        Busy <='1';
      elsif (pDinBEn = '1') then
        ShiftReg <= "1000" & pDInB;
        LoadDelayReg(0) <= '1';
        DAC_Clk <= '0';
        pDAC_nCS <= '0';
        Busy <='1';
      end if;

    end if;
  end process State;

  pBusy <= Busy;
  pDAC_Clk <= DAC_Clk;
  pDAC_SDI <= ShiftReg(15);

end RTL;
