Open Slatyo opened 7 months ago
SPI Setup:
Constraint:
# SPI Configuration
net SCLK loc = p2;
net MOSI loc = p65;
net MISO loc = p1;
net CS loc = p6;
SPI:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
entity SPI_Interface is
Port (
CLK : in STD_LOGIC; -- Global clock input
SCLK : out STD_LOGIC; -- SPI Clock
MOSI : out STD_LOGIC; -- Master Out Slave In
MISO : in STD_LOGIC; -- Master In Slave Out
CS : out STD_LOGIC; -- Chip Select
START : in STD_LOGIC; -- Start signal for SPI communication
DATA_OUT : out STD_LOGIC_VECTOR(11 downto 0); -- ADC Data output
BUSY : out STD_LOGIC -- Indicates SPI is in operation
);
end SPI_Interface;
architecture Behavioral of SPI_Interface is
signal clk_count : integer := 0;
signal spi_state : integer := 0;
signal mosi_data : STD_LOGIC_VECTOR(15 downto 0);
signal recv_data : STD_LOGIC_VECTOR(15 downto 0);
constant CLK_DIV : integer := 10; -- SPI Clock division factor
begin
process(CLK)
begin
if rising_edge(CLK) then
-- Clock Divider for SPI Clock
if clk_count < CLK_DIV then
clk_count <= clk_count + 1;
else
clk_count <= 0;
SCLK <= not SCLK;
-- SPI State Machine
case spi_state is
when 0 =>
if START = '1' then
CS <= '0'; -- Activate CS to start transmission
mosi_data <= "0000011000000000"; -- Command for Channel 0
spi_state <= 1;
BUSY <= '1';
end if;
when 1 to 16 =>
-- Sending Command Bit by Bit
if clk_count = 0 then -- Change MOSI on falling edge of SCLK
MOSI <= mosi_data(16 - spi_state);
spi_state <= spi_state + 1;
end if;
when 17 to 32 =>
-- Receiving Data Bit by Bit
if clk_count = CLK_DIV/2 then -- Sample MISO at rising edge of SCLK
recv_data(32 - spi_state) <= MISO;
spi_state <= spi_state + 1;
end if;
when 33 =>
CS <= '1'; -- Deactivate CS
DATA_OUT <= recv_data(11 downto 0); -- Output the received ADC data
BUSY <= '0';
spi_state <= 0;
when others =>
spi_state <= 0;
end case;
end if;
end if;
end process;
end Behavioral;
Create UserContraint files for all the pins once we have the Pin Layout.