实现时钟的二分频,四分频
1.时钟分频模块:
module clk_div(input clk, //50Mhzinput rst_n,input [15:0] lcd_id,output reg lcd_pclk);reg clk_25m;
reg clk_12_5m;
reg div_4_cnt;//时钟2分频 输出25MHz时钟
always @(posedge clk or negedge rst_n) beginif(!rst_n)clk_25m <= 1'b0;else clk_25m <= ~clk_25m;
end//时钟4分频 输出12.5MHz时钟
always @(posedge clk or negedge rst_n) beginif(!rst_n) begindiv_4_cnt <= 1'b0;clk_12_5m <= 1'b0;end else begindiv_4_cnt <= div_4_cnt + 1'b1;if(div_4_cnt == 1'b1)clk_12_5m <= ~clk_12_5m;end
endalways @(*) begincase(lcd_id)16'h4342 : lcd_pclk = clk_12_5m;16'h7084 : lcd_pclk = clk_25m; 16'h7016 : lcd_pclk = clk;16'h4384 : lcd_pclk = clk_25m;16'h1018 : lcd_pclk = clk;default : lcd_pclk = 1'b0;endcase
endendmodule
2.tb:
module clk_div_tb;// Parameters
localparam CLK_PERIOD = 20; // 50MHz clock period// Inputs
reg clk;
reg rst_n;
reg [15:0] lcd_id;// Outputs
wire lcd_pclk;// 实例化被测试模块
clk_div u_clk_div(.clk(clk), .rst_n(rst_n), .lcd_id(lcd_id), .lcd_pclk(lcd_pclk)
);initial begin// 初始化clk = 0;rst_n = 0;lcd_id = 0;// 等待100纳秒用于全局复位#100;rst_n = 1; // 释放复位// 改变lcd_id的值来测试不同的时钟分频情况#(CLK_PERIOD*5); // 等待5个时钟周期lcd_id = 16'h4342; // 测试12.5MHz输出#(CLK_PERIOD*5);lcd_id = 16'h7084; // 测试25MHz输出#(CLK_PERIOD*5);lcd_id = 16'h7016; // 测试50MHz输出#(CLK_PERIOD*5);lcd_id = 16'h4384; // 再次测试25MHz输出#(CLK_PERIOD*5);lcd_id = 16'h1018; // 再次测试50MHz输出#(CLK_PERIOD*5);lcd_id = 16'h0000; // 默认情况,输出低电平
end// 时钟信号生成
always #(CLK_PERIOD/2) clk = ~clk; // 50MHz时钟信号endmodule
3.仿真: