Verilog HDL write SPI slave communication

Source: Internet
Author: User

Module Spi_slave (
CLK,//system clock 50MHz
SCK, Ssel, MOSI,MISO//SPI communication pin

                 );
Input SCK, Ssel, MOSI;
Output miso;

Sync SCK to the FPGA clock using a 3-bits shift register
reg [2:0] Sckr;
Always @ (Posedge clk) Sckr <= {sckr[1:0], SCK};
Wire Sck_risingedge = (sckr[2:1]==2 ' B01); Now we can detect SCK rising edges
Wire Sck_fallingedge = (sckr[2:1]==2 ' B10); and falling edges

//Same thing for Ssel
reg [2:0] SSELR;
Always @ (Posedge clk) sselr <= {sselr[1:0], ssel};
Wire ssel_active = ~sselr[1]; Ssel is active low
Wire Ssel_startmessage = (sselr[2:1]==2 ' B10); Message starts at falling edge
Wire Ssel_endmessage = (sselr[2:1]==2 ' B01); Message stops at rising Edge

//And for MOSI
reg [1:0] MOSiR;
Always @ (Posedge clk) MOSiR <= {mosir[0], MOSI};
Wire mosi_data = mosir[1];
reg [2:0] bitcnt; We handle SPI in 8-bits format, so we need a 3 bits counter to count the bits as they come in
-------------------Receive Data-------------------------------------------------

Reg Byte_received; High if a byte has been received
reg [7:0] byte_data_received,rev_data;

reg [7:0] byte_data_sent,sent_data;

Always @ (Posedge CLK)
Begin
if (ssel_active)
Begin
if (ssel_startmessage)
Byte_data_sent <= Sent_data;
End
if (~ssel_active)
Begin
bitcnt <= 3 ' b000;
Byte_data_sent <= 8 ' h00; After that, we send 0s///////////
End
Else
if (Sck_risingedge)
Begin
bitcnt <= bitcnt + 3 ' b001;
Byte_data_received <= {byte_data_received[6:0], mosi_data}; Implement a Shift-left

//register (since we receive the data MSB first)
Byte_data_sent <= {byte_data_sent[6:0], 1 ' b0};///////////

End
End
Always @ (Posedge clk) byte_received <= ssel_active && sck_risingedge && (bitcnt==3 ' b111);

//-----------------------receive data---------------------

Always @ (Posedge CLK)
if (byte_received)
Begin
Rev_data <= byte_data_received;

End

//-----------------------Send data----------------------
Assign miso = byte_data_sent[7]; Send MSB First
Endmodule

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.