Skip to content

Instantly share code, notes, and snippets.

@bit-hack
Created August 10, 2021 20:53
Show Gist options
  • Save bit-hack/86a5e21d4a72b0eaca3b87a54c859a73 to your computer and use it in GitHub Desktop.
Save bit-hack/86a5e21d4a72b0eaca3b87a54c859a73 to your computer and use it in GitHub Desktop.
spi slave
module spi_slave(input CLK, // system clock
input SPI_CLK, // spi clock
input SPI_MOSI, // spi mosi
input SPI_CS, // spi chip select
output [7:0] DATA, // data out
output RECV); // data received
reg [2:0] sclk;
reg [2:0] smosi;
reg [2:0] scs;
reg [7:0] sr; // internal shift register
reg [2:0] count; // bit count
reg avail; // data available
assign RECV = avail;
assign DATA = sr;
wire sclk_up = !sclk[2] & sclk[1];
wire sclk_down = !sclk[1] & sclk[2];
always @(posedge CLK) begin
sclk <= { sclk[1:0], SPI_CLK };
smosi <= { smosi[1:0], SPI_MOSI };
scs <= { scs[1:0], SPI_CS };
end
always @(posedge CLK) begin
if (sclk_up) begin // spi clock goes high
sr <= { sr[6:0], smosi[2] }; // shift data in
end
end
always @(posedge CLK) begin
avail <= 0;
if (sclk_down) begin // spi clock goes low
if (count == 0) begin // multiple of 8 bits shifted in
avail <= 1;
end
end
end
always @(posedge CLK) begin
if (!scs[2]) begin // cs goes low
if (sclk_up) begin // spi clock goes high
count <= count + 'd1;
end
end else begin
count <= 0; // reset counter
end
end
endmodule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment