module spi_ctrl(
input wire sclk,//系统时钟
input wire rst_n,
input wire work_en,
output wire spi_clk,
output wire spi_sdi,
output wire spi_csn,
input wire spi_sdo
);
parameter IDLE = 5’b0_0001;
parameter WAIT = 5’b0_0010;
parameter R_MEM= 5’b0_0100;
parameter W_REG= 5’b0_1000;
parameter STOP = 5’b0_0000;
parameter H_DIV_CYC = 5’d25-1;//分频器(要给他写一个寄存器)实现分频50倍
reg [4:0] state;//状态机的寄存器变量,独热码,5个bit
reg [4:0] div_cnt;
reg clk_p=1’b1
wire clk_n;//输出数据的时钟上升沿输出(与sclk相位相反)
reg pose_flag;
reg [3:0] wait_cnt;
reg [3:0] shift_cnt;//16位数据
reg [4:0] r_addr;
wire [15:0] r_data;
wire wren;
reg [15:0] shif_buf;
reg data_end;
//分频计数器
always @(posedge sclk or negedge rst_n)//异步组合逻辑
if(rst_n == 1’b0)
div_cnt <=5’d0;//复位的时候给他清零
else if(div_cnt == H_DIV_CYC )//计到24的时候清0
div_cnt <= 'd0;
else
div_cnt <= div_cnt + 1’b1;//一个加法器(未达到最大值累加)
//分频时钟不允许做寄存器的触发时钟,也就四不能写在alwaysk块的触发列表中
always @(posedge sclk or negedge rst_n)
if(rst_n == 1’b0)
clk_p <= 1’b0;
else if(div_cnt == H_DIV_CYC)
clk_p <= ~clk_p;//24反转一次一个周期就是50
assign clk_n=~clk_p;
always @(posedge sclk or negedge rst_n)
if(rst_n == 1’bo)
pose_flag <= 1’b0;
else if(clk_p == 1’b0&&div_cnt == H_DIV_CYC)
pose_flag <= 1’b1;
else pose_flag <= 1’b0;
always @(posedge sclk or negedge rst_n)//wait
if(rst_n == 1’b0)
wait_cnt<='d0;
else if(state == WAIT&&pose_flag == 1’b1)
wait_cnt <= wait_cnt + 1’b1;
else if(state !=WAIT)
wait_cnt <= 4’d0;
//fsm两段式
always @(posedge sclk or negedge rst_n)
if(rst_n == 1’b0)
state <= IDLE;
else case(state)
IDLE :if(work_en == 1’b1)
state <= WAIT;
WAIT :if(wait_cnt[3] == 1’b1)//记到8的时候
state <= R_MEM;
R_MEM:state <= W_REG;
W_REG:if(shift_cnt == 4’d15&&pose_flag == 1&&data_end!=1’d1)//写16个biit8个命令8个数据
state <= WAIT;
else if(shift_cnt == 4’d15&&pose_flag == 1&&data_end =1’d1)
state <= STOP;
STOP: state <= STOP;
default:state <= IDLE;
endcase
always @(posedge sclk or negedge rst_n)//移位寄存器
if(rst_n == 1’b0)
shift_cnt <= 'd0;
else if(state == W_REG && pose_flag == 1’b1)
shift_cnt <=shift_cnt +1’b1;
else if( state !=W_REG)
shift_cnt <= 4’d0;
//读mem的地址产生
always @(posedge sclk or negedge rst_n)
if(rst_n == 1’b0)
r_addr <= 'd0;
else if(state == R_MEM)
r_addr
assign wren =1’b0;
always @(posedge sclk or negedge rst_n)
if(rst_n == 1’b0)
shif_buf<='d0;
else if(state == R_MEM)
shif_buf<=r_data;
else if(state == W_REG&&pose_flag ==1’b1)
shif_buf <= {shif_buf[14:0]
ram_1632_sr ram_1632_sr_inst (
.address ( address_sig ),//读地址
.data ( 16’d0 ),//写数据
.inclock ( sclk ),
.wren ( wren ),//写使能高有效
.q ( r_data )
);
endmodule