---------------------------------------------------------------------------
-- NDT Solutions Ltd. Proprietary Information
-- Company Confidential
-- Copyright 2007
--
-- Filename: Spi16.vhd
-- Language: VHDL '93
-- Project:  NDTS2100
--
-- Design Description:
-- 16 data SPI interface
--
-- The clock will be 2*gHCycle input clock cycles long
---------------------------------------------------------------------------

library IEEE;
use IEEE.Std_Logic_1164.all;
use IEEE.Std_Logic_Arith.all;

entity Spi16 is
  generic(gHCycle: integer := 2);
  port(nReset    : in  std_ulogic;
       Clk       : in  std_ulogic;
       Wr        : in  std_ulogic;
       Data      : in  std_logic_vector(15 downto 0);
       Busy      : out std_ulogic;
       --
       SClk      : out std_ulogic;
       SData     : out std_ulogic;
       nSync     : out std_ulogic);
end entity Spi16;


architecture Rtl of Spi16 is

  signal ClkCount: integer range 0 to gHCycle*2;
  signal BitCount: integer range 0 to 16;
  signal ShiftReg: std_logic_vector(15 downto 0);
begin

  StateM: process(nReset, Clk)
  begin
    if nReset = '0' then
      ClkCount <= 0;
      BitCount <= 0;
      ShiftReg <= (others => '0');
      Busy <= '0';
      SClk <= '1';
      SData <= '0';
      nSync <= '1';
    elsif rising_edge(Clk) then
      if BitCount /= 0 then
        if ClkCount = 0 then
          nSync <= '0';
          SClk <= '1';
          SData <= ShiftReg(15);
          ShiftReg <= ShiftReg(14 downto 0) & '0';
        end if;
        if ClkCount = gHCycle then
          SClk <= '0';
        end if;
        if ClkCount = (gHCycle*2)-1 then
          ClkCount <= 0;
          BitCount <= BitCount - 1;
        else
          ClkCount <= ClkCount + 1;
        end if;
      elsif Wr = '1' then
        BitCount <= 16;
        ShiftReg <= Data;
        Busy <= '1';
      else
        nSync <= '1';
        Busy <= '0';
      end if;
    end if;
  end process StateM;

end architecture rtl;
