Skip to content

Instantly share code, notes, and snippets.

@bit-hack
Last active April 28, 2022 20:37
Show Gist options
  • Save bit-hack/ad3b67f1d58245d0a38fd6225c057b1d to your computer and use it in GitHub Desktop.
Save bit-hack/ad3b67f1d58245d0a38fd6225c057b1d to your computer and use it in GitHub Desktop.
spi slave device
module spiSlave(
input iClk, // master clock
input iSck, // spi clock (sample posedge)
input iCs, // spi chip select (active low)
input iMosi, // master out slave in
input [7:0] iData, // data transmit
output oMiso, // master in slave out
output [7:0] oData, // data received
output oAvail // data received strobe
);
reg [2:0] srSck;
reg [2:0] srCs;
reg [2:0] srMosi;
reg [7:0] srMiso;
assign oMiso = srMiso[7];
always @(posedge iClk) begin
if (negedge_cs) begin
srMiso <= iData;
end else begin
if (negedge_sck) begin
srMiso <= (counter == 0) ? { iData } : // latch new data
{ srMiso[6:0], 1'b0 }; // shift out
end
end
end
always @(posedge iClk) begin
srSck <= { srSck [1:0], iSck };
srCs <= { srCs [1:0], iCs };
srMosi <= { srMosi[1:0], iMosi };
end
reg posedge_sck;
reg negedge_sck;
reg negedge_cs;
always @(posedge iClk) begin
posedge_sck <= (srSck[2] == 'b0 && srSck[1] == 'b1);
negedge_sck <= (srSck[2] == 'b1 && srSck[1] == 'b0);
negedge_cs <= (srCs [2] == 'b1 && srCs [1] == 'b0);
end
reg [7:0] srData;
assign oData = srData;
always @(posedge iClk) begin
if (posedge_sck) begin
srData <= { srData[6:0], srMosi[2] };
end
end
reg [2:0] counter;
always @(posedge iClk) begin
counter <= negedge_cs ? 3'd0 :
posedge_sck ? counter + 3'd1 :
counter;
end
reg avail;
assign oAvail = avail;
always @(posedge iClk) begin
avail <= (srCs[2] == 0) && (counter[2:0] == 3'd7) && posedge_sck;
end
endmodule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment