`default_nettype none /* SPI slave shift reg a shift reg. rising edge shift clock shift when latch lo, store on latch upedge. ____ ____ latch \_______________/ _ _ _ _ sck _____/ \_/ \_/ \_/ \_____ pdatain->sreg ^ sreg->pdataout ^ shift left ^ ^ ^ ^ (dout=MSB) (LSB<=din) */ module spis #(parameter WID = 4) ( input wire din, output reg dout, input wire latch, input wire rst, input wire sck, input wire [WID-1:0]pdatain, output reg [WID-1:0]pdataout ); reg [WID-1:0] srg; reg change; reg follow; wire firstbit; assign firstbit=(change!=follow); always @(posedge latch or posedge rst) if(rst) pdataout<=0; else pdataout<=srg; always @(negedge latch or posedge rst) if(rst) change<=0; else change<=~follow; always @(posedge sck or posedge rst) if(rst) srg<=0; else if(firstbit)//true on first clock after latch lo srg<={pdatain,din}; else srg<={srg,din}; always @(posedge sck or posedge rst) if(rst) follow=0; else if(firstbit) follow<=change; else follow<=follow; always @* if(firstbit) dout=pdatain[WID-1]; else dout=srg[WID-1]; endmodule