企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
` `根据计数值,求所需计数器的位宽。自己写一个函数完成该任务。 ``` // function called clogb2 that returns an integer which has the // value of the ceiling of the log base 2 function integer clogb2 (input integer bit_depth); begin for(clogb2=0; bit_depth>0; clogb2=clogb2+1) bit_depth = bit_depth >> 1; end endfunction ``` ` `使用时需要在形参中减1。比如求计数4个数所需要寄存器位宽则为`w = clogb2(4-1)`。 ``` ` `实例 module data ( input clk, input rst_n, input sig, input din, output reg [1:0]cnt, output reg [3:0]data_0, output reg [3:0]data_1, output finish, output reg sig_d1, output reg sig_d2, output sig_p, output sig_n, output [12 :0]t_clogb2 ); // function called clogb2 that returns an integer which has the // value of the ceiling of the log base 2 function integer clogb2 (input integer bit_depth); begin for(clogb2=0; bit_depth>0; clogb2=clogb2+1) bit_depth = bit_depth >> 1; end endfunction parameter integer N = clogb2(7-1); wire [N:0]ty; assign ty = {N{1'b1}}; assign t_clogb2 = ty; assign sig_p = sig_d1 & (~sig_d2);//上升沿检测 assign sig_n = sig_d2 & (~sig_d1);//下降沿检测 always@(posedge clk) begin if(rst_n == 1'b0)begin sig_d1<= 1'b0; sig_d2 <= 1'b0; end else begin sig_d1<=sig; sig_d2 <=sig_d1; end end reg finish_flag; assign finish = finish_flag; //assign data_1 = finish ? data_0:data_1; always@(posedge clk) if(rst_n == 1'b0)begin cnt <= 2'd0; finish_flag <= 1'b0; end else begin case(cnt) 2'd0:begin data_0[3] <= din; finish_flag<=1'b0; end 2'd1:begin data_0[2] <= din; finish_flag<=1'b0; end 2'd2:begin data_0[1] <= din; finish_flag<=1'b0; end 2'd3:begin data_0[0] <= din; finish_flag<=1'b1; end endcase cnt <= cnt + 1'b1; if(finish_flag) data_1 = data_0; else data_1 = data_1; end endmodule ``` ![](https://img.kancloud.cn/3e/26/3e263a6aaca3659e16d078f14971cdeb_1316x531.png)