Skip to content

adaptableCoder/SPI-Verilog

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 

Repository files navigation

SPI Master Module (Mode 0) - Verilog

A robust, parameterizable SPI Master written in Verilog. This module is designed for standard SPI Mode 0 communication (CPOL = 0, CPHA = 0), ensuring clean clock generation, and stable back-to-back transfers.

Features

  • Fully Parameterizable: Easily adjust the system clock frequency, SPI bus frequency, and data width to fit any application.
  • SPI Mode 0 Compliant: Shifts data out on the falling edge of SCLK and samples data in on the rising edge.
  • Clean Clock Generation: Divides the system clock to generate a glitch-free SCLK safely within the standard synchronous logic domain.
  • Continuous Burst Support: Capable of back-to-back data transfers if the start signal is held high, automatically pulsing the Chip Select (CS).
  • Safe Hardware Reset: Can safely abort mid-transfer and recover to an idle state using a synchronous reset, preventing bus lock-ups.

Module Parameters

Parameter Default Value Description
clk_freq 50000000 (50 MHz) The frequency of the main system clock (clk).
spi_clk_freq 1000000 (1 MHz) The target frequency for the SPI clock (SCLK).
data_width 8 The number of bits per SPI transaction.

Port Map

Port Direction Width Description
clk Input 1 Main system clock.
reset Input 1 Synchronous active-high reset.
start Input 1 Pulse high to start a transaction. Hold high for back-to-back bursts.
data_in Input data_width Data byte to be transmitted (sent MSB first).
MISO Input 1 Master In Slave Out (Data received from slave).
SCLK Output 1 SPI Clock generated by the master.
MOSI Output 1 Master Out Slave In (Data sent to slave).
CS Output 1 Active-low Chip Select.
data_out Output data_width Fully received data byte from the slave. Valid after CS goes high.

Usage Example

wire [7:0] rx_data;
wire spi_sclk, spi_mosi, spi_cs;

spi_master #(
    .clk_freq(50_000_000),    // 50 MHz system clock
    .spi_clk_freq(1_000_000), // 1 MHz SPI clock
    .data_width(8)            // 8-bit data transfers
) my_spi_master (
    .clk(sys_clk),
    .reset(sys_rst),
    .start(start_tx),
    .data_in(8'hC3),
    .MISO(spi_miso),
    .SCLK(spi_sclk),
    .MOSI(spi_mosi),
    .CS(spi_cs),
    .data_out(rx_data)
);

Running the Simulation

Make sure Icarus Verilog and GTKWave are installed on your system.

iverilog -o sim design.v tb.v
vvp sim
gtkwave spi_master_tb.vcd

(A sample testbench tb.v is provided to drive the SPI Master (design.v) and generate the spi_master_tb.vcd waveform file for analysis.)

Example output waveform

SPI Master Waveform

State Machine Diagram

SPI FSM Diagram

About

SPI Master module (Mode 0) written in verilog

Topics

Resources

Stars

Watchers

Forks

Contributors

Languages