-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspi_slave.v
134 lines (121 loc) · 2.36 KB
/
spi_slave.v
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
module spi_slave(clk,rst_n,ss_n,mosi,tx_valid,tx_data,rx_data,rx_valid,miso);
parameter IDLE=3'b000;
parameter CHK_CMD=3'b001;
parameter WRITE=3'b010;
parameter READ_ADD=3'b011;
parameter READ_DATA=3'b100;
input clk,rst_n,ss_n,mosi,tx_valid;
input [7:0] tx_data;
output reg rx_valid,miso;
output reg [9:0]rx_data;
reg [3:0] count,count_2;
reg add_or_data;
reg [9:0] bus;
reg [7:0] bus2;
(* fsm_encoding ="sequential" *)
reg [2:0] cs ,ns;
always @(posedge clk or negedge rst_n) begin
if (~rst_n) begin
cs<= IDLE;
end
else
cs<=ns;
end
always @(*)begin
case(cs)
IDLE:begin
if(ss_n)
ns=IDLE;
else
ns=CHK_CMD;
end
CHK_CMD:begin
if(ss_n)
ns=IDLE;
else begin
if(mosi)begin
if(add_or_data)
ns<=READ_DATA;
else begin
ns<=READ_ADD;
end
end
else begin
ns<=WRITE;
end
end
end
WRITE:begin
if(ss_n)
ns=IDLE;
else
ns=WRITE;
end
READ_ADD:begin
if(ss_n)
ns=IDLE;
else
ns=READ_ADD;
end
READ_DATA:begin
if(ss_n)
ns=IDLE;
else
ns=READ_DATA;
end
default:begin
ns=IDLE;
end
endcase
end
always @(posedge clk)begin
case(cs)
WRITE:begin
bus[count-1]<=mosi;
count<=count-1;
if(count==0)begin
count<=10;
rx_valid<=1;
rx_data<=bus;
end
end
READ_ADD:begin
bus[count-1]<=mosi;
count<=count-1;
if(count==0)begin
count<=10;
rx_valid<=1;
rx_data<=bus;
add_or_data<=1;
end
end
READ_DATA:begin
if(~tx_valid)begin
bus[count-1]<=mosi;
count<=count-1;
if(count==0)begin
count<=10;
rx_valid<=1;
rx_data<=bus;
add_or_data<=0;
end
end
else begin
bus2<=tx_data;
miso<=bus2[count_2-1];
count_2=count_2-1;
if(count_2==0)
count_2<=8;
end
end
IDLE:begin
rx_valid<=0;
count<=10;
count_2<=8;
miso<=0;
bus<=0;
bus2<=0;
end
endcase
end
endmodule