-
Notifications
You must be signed in to change notification settings - Fork 0
/
spi_protocol.v
63 lines (55 loc) · 1.65 KB
/
spi_protocol.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
module spi_master (
input wire clk,
input wire rst,
input wire [7:0] data_in,
input wire start,
input wire miso,
input wire [N-1:0] cs, // N is the number of slaves
output reg spi_clk,
output reg mosi,
output reg [7:0] data_out,
output reg done
);
parameter N = 4; // Define the number of slaves
reg [2:0] bit_cnt;
reg [7:0] shift_reg;
reg [1:0] state;
localparam IDLE = 2'b00,
TRANSFER = 2'b01,
DONE = 2'b10;
always @(posedge clk or posedge rst) begin
if (rst) begin
spi_clk <= 0;
mosi <= 0;
data_out <= 0;
done <= 0;
bit_cnt <= 0;
state <= IDLE;
end else begin
case (state)
IDLE: begin
if (start) begin
shift_reg <= data_in;
bit_cnt <= 0;
state <= TRANSFER;
end
done <= 0;
end
TRANSFER: begin
spi_clk <= ~spi_clk;
if (spi_clk) begin
mosi <= shift_reg[7];
shift_reg <= {shift_reg[6:0], miso};
bit_cnt <= bit_cnt + 1;
if (bit_cnt == 7) state <= DONE;
end
end
DONE: begin
data_out <= shift_reg;
done <= 1;
state <= IDLE;
end
endcase
end
end
endmodule