FPGA SPI

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

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值