入门数字IC必会的小案例——时钟分频
module div_clk_4(
input wire clk,
input wire rst,
output reg clk_4
);
reg [1:0] clk_cnt;
always @(posedge clk) begin
if (rst == 1'b1) begin
clk_cnt <= 2'd0;
end
else if (clk_cnt == 2'd3) begin
clk_cnt <= 2'd0;
end
else begin
clk_cnt <= clk_cnt + 1'b1;
end
end
always @(posedge clk) begin
if (rst == 1'b1) begin
clk_4 <= 1'b0;
end
else if (clk_cnt == 2'd1) begin
clk_4 <= 1'b1;
end
else if (clk_cnt == 2'd3) begin
clk_4 <= 1'b0;
end
end
endmodule
代码原理:
① 输入CLK,rst(高电平有效)
② 在每个时钟上升沿计数,计数器名为clk_cnt,计数周期0,1,2,3;
③ 当计数器计数达到1,四分频时钟变成1,当计数器计数达到3,四分频时钟为0。
testbench代码如下:
`timescale 1ns/1ns
module tb_div_clk_4();
reg clk,rst;
wire clk_4;
initial begin
clk = 0;
rst = 1;
# 100;
rst = 0;
end
always #10 clk = ~clk;
div_clk_4 div_clk_4_inst(
.clk(clk),
.rst(rst),
.clk_4(clk_4)
);
endmodule
仿真波形: