【作业要求】
1、简述SPI的特点:
(1)传输速率快:一般可达几十Mbps,属于较高速的同步串行通信总线。
(2)通信方式简单、线数少:通常采用4根线通信,即SCLK、MOSI、MISO、CS;也有设备采用3线半双工通信方式。
(3)同步边沿采样:由时钟信号同步,通过CPOL/CPHA配置,可在上升沿或下降沿采样。
(4)无应答机制:SPI本身没有应答/确认机制,可靠性相对有限,通常需要依靠片选控制、时序设计、PCB信号完整性和软件校验来保证通信稳定。
(5)支持一主一从和一主多从:一主多从时通常共享SCLK、MOSI、MISO,各从设备使用独立片选CS。
2、请写出SPI接收端的详细代码?
`timescale 1ns / 1ps
module SPI_RX#(
parameter delay = 40,//分频周期
parameter CPOL = 0 ,//时钟极性
parameter CPHA = 0 //时钟相位
)
input sysclk ,//系统时钟
input rst_n ,//系统复位--低电平有效
input spi_req ,//起始信号(通信请求),拉高将CS拉低,开始接收
input [7:0] byte_num ,//字节数,表示接收多少个字节的数据
input MISO ,//数据线:主机输入,从机输出,接收从机数据
output reg [7:0] data_out ,//输出的8bit数据
output reg rx_done ,//信号拉高表示此次接收通信完成
//----四线SPI接口(主机输出)----//
output reg CS ,//片选信号线,低电平有效
output reg SCK //时钟线,用于同步数据
);
//内部信号声明
localparam MID = delay >> 1;//半个分频周期
reg [5:0] cnt_sck ;//分频周期计数器
reg [2:0] cnt_bit ;//bit为计数器
reg [7:0] cnt_byte;//字节计数器
wire spi_rise_flag;//检测spi_req的上升沿
reg spi_req_reg1,spi_req_reg2;//对spi_req打两拍
wire [31:0]spi_rise_delay;//采集数据延迟
assign spi_rise_delay = (CPHA == 0) ? (MID - 1) : (delay - 1);
always @(posedge sysclk)
begin
if(!rst_n)begin
spi_req_reg1 <= 0;
spi_req_reg2 <= 0;
end
else
begin
spi_req_reg1 <= spi_req ;
spi_req_reg2 <= spi_req_reg1;
end
end
assign spi_rise_flag = spi_req_reg1 && ~spi_req_reg2;
always @(posedge sysclk )
begin
if(!rst_n)
CS <= 1;
else if(spi_rise_flag == 1)
CS <= 0;
else if(rx_done == 1)
CS <= 1;
else
CS <= CS;
end
always @(posedge sysclk)
begin
if(!rst_n)
cnt_sck <= 0;
else if(CS == 0)begin
if(cnt_sck == delay - 1)
cnt_sck <= 0;
else
cnt_sck <= cnt_sck + 1;
end
else
cnt_sck <= 0;
end
always @(posedge sysclk )
begin
if(!rst_n)
SCK <= CPOL;
else if(CS == 0)begin
if(cnt_sck == MID - 1)
SCK <= ~CPOL;
else if(cnt_sck == delay - 1)
SCK <= CPOL;
else
SCK <= SCK;
end
else
SCK <= CPOL;
end
always@(posedge sysclk)
if(!rst_n)
cnt_bit <= 0;
else if(CS == 0)begin
if(cnt_sck == delay - 1)begin
if(cnt_bit == 7)
cnt_bit <= 0;
else
cnt_bit <= cnt_bit + 1;
end
else
cnt_bit <= cnt_bit;
end
else
cnt_bit <= 0;
always @(posedge sysclk )
begin
if(!rst_n)
cnt_byte <= 0;
else if(CS == 0)begin
if((cnt_sck == delay - 1) && (cnt_bit == 7))begin
if(cnt_byte == byte_num - 1)
cnt_byte <= 0;
else
cnt_byte <= cnt_byte + 1;
end
else
cnt_byte <= cnt_byte;
end
else
cnt_byte <= 0;
end
always @(posedge sysclk)
begin
if(!rst_n)
data_out <= 8'd0;
else if(CS == 0)begin
if(cnt_sck == spi_rise_delay)
data_out <= {data_out[6:0],MISO};
else
data_out <= data_out;
end
else
data_out <= 8'd0;
end
always @(posedge sysclk )
begin
if(!rst_n)
rx_done <= 0;
else if ((CS == 0) && (cnt_sck == delay - 1) && (cnt_bit == 7) && (cnt_byte == byte_num - 1))
rx_done <= 1;
else
rx_done <= 0;
end
评论 0