spi 10方式编写
//第一个CS变低的时候要sclk为高电平,第一个跳变沿进行赋值
module spi
(
input clk,
input rst_n,
output reg sclk,
output reg cs,
output reg sdin
);
reg [2:0]cnt;
reg [5:0]state;
reg[1:0]s;
reg[7:0] sanjiao_out;
reg[7:0] num;
always@(negedge cs or negedge rst_n)
begin if(!rst_n) begin num<=0; s<=0; end
else
begin case(s)
0:begin if(num==255)s<=1;else num<=num+5;end
1:begin if(num==0)s<=0;else num<=num-5; end
default:begin s<=0;num<=0;end
endcase
end
end
always@(posedge clk or negedge rst_n)
begin
if(!rst_n)begin cnt<=0;sclk<=1;end
else if(cnt==4)begin cnt<=0;sclk<=1;end
else if(cnt<=2)begin cnt<=cnt+1;sclk<=1;end
else begin cnt<=cnt+1;sclk<=0;end
end
reg [15:0] data;
always @(posedge clk or negedge rst_n)
if(!rst_n)begin state<=0; cs=1;sdin=0;end
else begin
case(state)
0: begin if(cnt==1)begin cs<=0;data={2'b00,num[7:0],6'b000000};state<=state+1;end else begin state<=0;cs<=1;end end
1:if(cnt==2) begin sdin<=data[15];state<=state+1;end
2:if(cnt==2) begin sdin<=data[14];state<=state+1;end
3:if(cnt==2) begin sdin<=data[13];state<=state+1;end
4:if(cnt==2) begin sdin<=data[12];state<=state+1;end
5:if(cnt==2) begin sdin<=data[11];state<=state+1;end
6:if(cnt==2) begin sdin<=data[10];state<=state+1;end
7:if(cnt==2) begin sdin<=data[9];state<=state+1;end
8:if(cnt==2) begin sdin<=data[8];state<=state+1;end
9:if(cnt==2) begin sdin<=data[7];state<=state+1;end
10:if(cnt==2) begin sdin<=data[6];state<=state+1;end
11:if(cnt==2) begin sdin<=data[5];state<=state+1;end
12:if(cnt==2) begin sdin<=data[4];state<=state+1;end
13:if(cnt==2) begin sdin<=data[3];state<=state+1;end
14:if(cnt==2) begin sdin<=data[2];state<=state+1;end
15:if(cnt==2) begin sdin<=data[1];state<=state+1;end
16:if(cnt==2) begin sdin<=data[0];state<=state+1;end
17:if(cnt==2)begin state<=0;cs<=1;end
endcase
end
endmodule