写在前面
承接本系列上文。整理一些简单的根据时序图编写Verilog代码的实例,帮助新手学习,老手巩固。每次更新两题,根据难度会挑选一些进行讲解。
题目11
题目11答案
类似前面10的设计,可以参考提供的三个版本
这里只贴出状态机版本:
module test11_2 ( input clk, // Clock input en1, // Clock Enable input rst_n, // Asynchronous reset active low output reg dout ); reg [4-1: 0] x; wire add_cnt; wire end_cnt; reg [3:0] cnt ; reg flag; assign add_cnt = flag==1; assign end_cnt = add_cnt && cnt==2*x-1; always @(posedge clk or negedge rst_n)begin if(!rst_n)begin cnt <= 0; end else if(add_cnt)begin if(end_cnt) cnt <= 0; else cnt <= cnt + 1; end end //-----------------状态机------------------- //--------------<状态机参数>---------------- parameter S0 =4'b0000, S1 =4'b0001, S2 =4'b0010, S3 =4'b0100; //---------------<信号定义>------------------ reg [4- 1 : 0] state_c, state_n; //设计转移条件 wire S0toS1_condition = state_c== S0 && end_cnt==1; wire S1toS2_condition = state_c== S1 && end_cnt==1; wire S2toS3_condition = state_c== S2 && end_cnt==1; //描述次态寄存器迁移到现态寄存器 always@(posedge clk or negedge rst_n)begin if(!rst_n)begin state_c <= S0; end else begin state_c <= state_n; end end //描述状态转移条件判断 always@(*)begin case(state_c) S0:begin if(S0toS1_condition)begin state_n = S1; end else begin state_n = state_c; end end S1:begin if(S1toS2_condition)begin state_n = S2; end else begin state_n = state_c; end end S2:begin if(S2toS3_condition)begin state_n = S3; end else begin state_n = state_c; end end S3:begin state_n = S0; end default:begin state_n = S0; end endcase end //输出 always @(*)begin if(rst_n==0)begin x<=0; end else if(state_c==S0)begin x<=3; end else if(state_c==S1)begin x<=2; end else if(state_c==S2)begin x<=1; end end always @(posedge clk or negedge rst_n)begin if(rst_n==1'b0)begin flag <=0; end else if(en1==1)begin flag <=1; end else if(state_c==S3)begin flag <=0; end else begin flag <=flag; end end reg doutr; always @(posedge clk or negedge rst_n)begin if(rst_n==0)begin doutr<=0; end else if(state_c==S3)begin doutr<=0; end else if(end_cnt==1)begin doutr<=0; end else if(cnt==x-1 && flag==1)begin doutr<=1; end end always @(posedge clk or negedge rst_n)begin if(rst_n==1'b0)begin dout<=0; end else begin dout<=doutr; end end endmodule
题目12
题目12答案
思路类似第一题
always @(posedge clk or negedge rst_n)begin if(!rst_n)begin cnt <= 0; end else if(add_cnt)begin if(end_cnt) cnt <= 0; else cnt <= cnt + 1; end end reg [2-1: 0] dout; assign add_cnt = dout == 2; assign end_cnt = add_cnt && cnt== 5-1; always @(posedge clk or negedge rst_n)begin if(rst_n == 1'b0)begin dout<= 0; end else if(en==1)begin dout<= 2; end else if(end_cnt==1)begin dout<= 0; end end