Home / Learn Chip Programming / SPI Master and Slave in Verilog
SPI Master and Slave in Verilog
Implement SPI hardware for a display, ADC or flash.
In shortImplement SPI hardware for a display, ADC or flash.
Theory in plain words
What it is
An SPI master generates SCLK, shifts MOSI out and samples MISO in. The clock is derived from the system clock with a divider (clock enable). Mode 0: sample on rising edge, change on falling edge.
Why we use it
Many FPGA peripherals (OLED, DAC, SD card) speak SPI. A simple master handles all.
How it works
State: idle, transfer N bits with a bit counter, toggle SCLK on divider ticks, shift register in/out, assert CS, flag done.
Where it is used
- OLED and TFT driver
- ADC readout (MCP3008)
- Flash reading
SPI timing builder
Transfer time and dividerTry it Yourself
Choose half = system clock / (2 x SCK). Always keep SCK below the slowest device limit.
module spi_master #(parameter HALF = 4) (input clk, start, input [7:0] tx_data, input miso, output reg sclk = 0, mosi = 0, cs_n = 1, output reg [7:0] rx_data, output reg done = 0);
reg [7:0] sh; reg [3:0] bit_i; reg [15:0] cnt; reg busy = 0;
always @(posedge clk) begin
done <= 0;
if (!busy) begin if (start) begin busy <= 1; cs_n <= 0; sh <= tx_data; mosi <= tx_data[7]; bit_i <= 0; cnt <= 0; end end
else if (cnt == HALF-1) begin
cnt <= 0; sclk <= ~sclk;
if (!sclk) rx_data <= {rx_data[6:0], miso}; // rising edge: sample
else begin // falling edge: change data
if (bit_i == 7) begin busy <= 0; cs_n <= 1; done <= 1; end
else begin bit_i <= bit_i + 1; sh <= sh << 1; mosi <= sh[6]; end
end
end else cnt <= cnt + 1;
end
endmoduleTip:Simulate with a testbench that has a fake slave echoing data. When it passes, connect the real device and check it with a logic analyzer.
Quick quiz
1. SPI mode 0 samples on...
CPOL 0, CPHA 0.
2. Clock divider is made with...
Counters divide the system clock.