Implement an SPI Slave Interface in Verilog for an FPGA
Write a mode 0 SPI slave in Verilog that samples SCK, CS and MOSI with the FPGA clock, shifts bytes in and out and is tested with a simulated SPI master.

An FPGA that sits behind a microcontroller usually talks to it over SPI, with the FPGA as the peripheral: the microcontroller drives the clock and chip select, and the FPGA must shift bytes in and out at whatever rate the controller chooses. There are two ways to build the receiver. The first clocks the logic directly from SCK, which is compact but makes SCK a clock domain of its own with all the timing and crossing problems that brings. The second treats SCK and the other SPI lines as ordinary asynchronous inputs, samples them with the FPGA's own clock and detects edges. That is the one this post builds, because it keeps the whole design in one clock domain, it is easy to simulate and it works on any FPGA without special clock routing. The cost is a speed limit: SCK must be slower than the system clock by a safe factor, derived below. The design is mode 0, eight bits per transfer, most significant bit first, written in Verilog-2001 and tested with Icarus Verilog 12.0.
The rules a mode 0 slave follows
In SPI mode 0 the clock idles low. The controller changes MOSI when SCK falls and the peripheral samples MOSI when SCK rises. The peripheral changes MISO when SCK falls and the controller samples MISO when SCK rises. Chip select is active low and marks the frame: the slave resets its bit counter whenever CS is high and presents the first bit of its reply before the first clock edge.
That last point is the one people get wrong. The first MISO bit has to be ready as soon as CS falls, because the first rising SCK edge is the controller's sampling instant. The next bit appears after the first falling edge.
Synchronise, then detect edges
Three asynchronous inputs enter the design: sck, cs_n and mosi. Each goes through a shift register of flip-flops clocked by the system clock. Two stages remove metastability for the practical purpose of this design, and a third stage on sck holds the previous value so edges can be found by comparing two consecutive samples.
module spi_slave (
input wire clk,
input wire rst,
input wire sck,
input wire cs_n,
input wire mosi,
output wire miso,
input wire [7:0] tx_data,
output reg [7:0] rx_data,
output reg rx_valid
);
reg [2:0] sck_sync;
reg [1:0] cs_sync;
reg [1:0] mosi_sync;
always @(posedge clk) begin
sck_sync <= {sck_sync[1:0], sck};
cs_sync <= {cs_sync[0], cs_n};
mosi_sync <= {mosi_sync[0], mosi};
end
wire sck_rise = (sck_sync[2:1] == 2'b01);
wire sck_fall = (sck_sync[2:1] == 2'b10);
wire active = ~cs_sync[1];
reg [2:0] bit_cnt;
reg [7:0] shift_in;
reg [7:0] shift_out;
always @(posedge clk) begin
rx_valid <= 1'b0;
if (rst || !active) begin
bit_cnt <= 3'd0;
shift_out <= tx_data;
end else begin
if (sck_rise) begin
shift_in <= {shift_in[6:0], mosi_sync[1]};
bit_cnt <= bit_cnt + 3'd1;
if (bit_cnt == 3'd7) begin
rx_data <= {shift_in[6:0], mosi_sync[1]};
rx_valid <= 1'b1;
end
end
if (sck_fall)
shift_out <= (bit_cnt == 3'd0) ? tx_data : {shift_out[6:0], 1'b0};
end
end
assign miso = active ? shift_out[7] : 1'bz;
endmoduleRead it as three small machines. The synchroniser block makes delayed copies of the inputs. sck_rise is true for exactly one system clock when the synchronised clock goes from 0 to 1, and sck_fall for the opposite. active is the synchronised chip select, inverted.
The main block resets the bit counter and reloads shift_out from tx_data whenever the slave is not selected. That reload is what puts the first bit on MISO before the first clock. On each rising edge it shifts the sampled MOSI into shift_in and counts; on the eighth edge it publishes the byte and pulses rx_valid for one system clock. On each falling edge it shifts shift_out left so the next bit appears, except after a complete byte (bit_cnt has wrapped to zero), when it reloads shift_out from tx_data so a multi-byte frame can answer each byte with fresh data. The reload happens at the falling edge, not at the rising one, because the controller is still sampling the last bit of the old byte at the rising edge. miso is tri-stated when the slave is deselected, so several slaves can share one MISO wire. If the FPGA's pad cannot tri-state in your design, drive a constant instead and let the board's wiring handle the sharing.
How fast can SCK run?
The synchronisers add delay. SCK is seen two to three system clocks after it changes, and MISO changes one more clock after that. The controller samples MISO at the next rising SCK edge, half an SCK period after the falling edge that triggered the change. The MISO update must therefore settle within half an SCK period, which leaves a budget of about four system clocks for the whole chain at the least. Keeping SCK at one eighth of the system clock or slower gives each half period four system clocks and a margin. A 100 MHz FPGA clock therefore supports an SCK of about 12 MHz in this design, and the practical figure also depends on pad and trace delays you should check against your timing report. If you need a faster SPI link, use the SCK-clocked design instead and cross the byte into the system domain with a handshake.
A testbench with a master task
The simulated master follows mode 0: change MOSI after SCK falls, raise SCK, sample MISO.
`timescale 1ns/1ps
module spi_slave_tb;
reg clk = 1'b0;
reg rst = 1'b1;
reg sck = 1'b0;
reg cs_n = 1'b1;
reg mosi = 1'b0;
wire miso;
wire [7:0] rx_data;
wire rx_valid;
reg [7:0] master_rx;
spi_slave dut (
.clk(clk), .rst(rst), .sck(sck), .cs_n(cs_n), .mosi(mosi), .miso(miso),
.tx_data(8'h3C), .rx_data(rx_data), .rx_valid(rx_valid)
);
always #5 clk = ~clk;
always @(posedge clk)
if (rx_valid)
$display("slave received 0x%02h", rx_data);
task spi_xfer(input [7:0] out_byte);
integer i;
begin
cs_n = 1'b0;
#200;
for (i = 7; i >= 0; i = i - 1) begin
mosi = out_byte[i];
#100 sck = 1'b1;
master_rx[i] = miso;
#100 sck = 1'b0;
end
#200 cs_n = 1'b1;
#200;
end
endtask
initial begin
#50 rst = 1'b0;
#100;
spi_xfer(8'hA5);
$display("master received 0x%02h", master_rx);
$finish;
end
endmoduleiverilog -g2012 -o spi_sim spi_slave.v spi_slave_tb.v
vvp spi_simslave received 0xa5
master received 0x3cSCK here has a 200 ns period, 5 MHz, against a 10 ns system clock, so the half-period is ten system clocks, well inside the rule above. The #200 after chip select falls gives the synchronisers time to see the frame start and the reload to put the first MISO bit out. Both bytes arrive intact: the slave sees 0xA5 and the master sees the 0x3C the slave offered. If you wanted to test the margin, shorten the half-period in the task until the numbers fail and see where the design breaks.
From bytes to a register map
A byte interface is not yet a protocol. The usual convention for register access over SPI is a command byte followed by data: bit 7 of the first byte says write (1) or read (0), bits 6 to 0 give the register address, and the second byte carries the data. A write sends 0x80 | addr and then the new value. A read sends addr and then any dummy byte, and the register's value comes back during that second byte. Because the slave reloads tx_data at the falling edge after each byte, the register block only has to put the right value on tx_data after seeing the command:
module spi_regs (
input wire clk,
input wire rst,
input wire cs_active,
input wire [7:0] rx_data,
input wire rx_valid,
output reg [7:0] tx_data,
output reg [7:0] reg0,
output reg [7:0] reg1
);
reg [1:0] phase;
reg wr;
reg [6:0] addr;
always @(posedge clk) begin
if (rst) begin
reg0 <= 8'h00;
reg1 <= 8'h00;
end
if (rst || !cs_active) begin
phase <= 2'd0;
tx_data <= 8'h00;
end else if (rx_valid) begin
case (phase)
2'd0: begin
wr <= rx_data[7];
addr <= rx_data[6:0];
tx_data <= (rx_data[6:0] == 7'd0) ? reg0 : reg1;
phase <= 2'd1;
end
2'd1: begin
if (wr) begin
if (addr == 7'd0) reg0 <= rx_data;
else reg1 <= rx_data;
end
phase <= 2'd2;
end
default: ;
endcase
end
end
endmoduleThe frames on the wire then look like this:
| Operation | MOSI bytes | MISO bytes |
|---|---|---|
| write 0x5A to register 1 | 81 5A | 00 then the old value of register 1 |
| read register 1 | 01 00 | 00 5A |
The first MISO byte is always the idle value, because the slave has not yet seen the command when it starts replying. That is a property of SPI, not of this design: the response is always one byte behind the request, so a read needs one clocked-out dummy byte. Firmware that forgets the dummy byte reads its own previous value, which is the commonest bug on the controller side.
Breaking it on purpose
Remove the #200 after cs_n = 1'b0 and the first MISO bit is sampled before the slave is active, while miso is still tri-stated, so the top bit of master_rx comes back unknown and the display shows an unknown digit instead of 0x3c. Make the system clock the same as SCK and the edge detectors never see a clean transition. A good test suite includes both, since they are the failures you meet on a real board.


