题解 | #任意小数分频#
任意小数分频
http://www.nowcoder.com/practice/24c56c17ebb0472caf2693d5d965eabb
- 首先确定小数分频的频率成分,以8.7为例,表示87个周期中有10个脉冲信号,87/10=8...7,因此需要9分频时钟7个和8分频时钟(10-7)个(数学推导不再赘述,可移步知乎)。
- 我的设计中为了功耗更低,大周期计数器改为计数分频后时钟的脉冲个数。
`timescale 1ns/1ns
module div_M_N(
input wire clk_in,
input wire rst,
output wire clk_out
);
//parameter
parameter M_N = 8'd87;
parameter c89 = 8'd24; // 8/9时钟切换点
parameter div_e = 5'd8; //偶数周期
parameter div_o = 5'd9; //奇数周期
//defination
reg clk_8;
reg clk_9;
reg [2 : 0] cnt_8;
wire add_cnt_8;
wire end_cnt_8;
reg [3 : 0] cnt_9;
wire add_cnt_9;
wire end_cnt_9;
reg [3 : 0] cnt_10;
wire add_cnt_10;
wire end_cnt_10;
//output
assign add_cnt_8 = (cnt_10 < 3);
assign end_cnt_8 = add_cnt_8 && (cnt_8 == div_e - 1);
always@(posedge clk_in or negedge rst)begin
if(!rst) cnt_8 <= 'd0;
else if(end_cnt_8) cnt_8 <= 'd0;
else if(add_cnt_8) cnt_8 <= cnt_8 + 1'b1;
end
assign add_cnt_9 = (cnt_10 > 2);
assign end_cnt_9 = add_cnt_9 && (cnt_9 == div_o - 1);
always@(posedge clk_in or negedge rst)begin
if(!rst) cnt_9 <= 'd0;
else if(end_cnt_9) cnt_9 <= 'd0;
else if(add_cnt_9) cnt_9 <= cnt_9 + 1'b1;
end
assign add_cnt_10 = end_cnt_8 | end_cnt_9;
assign end_cnt_10 = add_cnt_10 && (cnt_10 == 10 - 1);
always@(posedge clk_in or negedge rst)begin
if(!rst) cnt_10 <= 'd0;
else if(end_cnt_10) cnt_10 <= 'd0;
else if(add_cnt_10) cnt_10 <= cnt_10 + 1'b1;
end
always@(posedge clk_in or negedge rst)begin
if(!rst) clk_8 <= 'd0;
else if((cnt_8 == 0 || cnt_8 == 4) && add_cnt_8) clk_8 <= ~clk_8;
end
always@(posedge clk_in or negedge rst)begin
if(!rst) clk_9 <= 'd0;
else if((cnt_9 == 0 || cnt_9 == 4) && add_cnt_9) clk_9 <= ~clk_9;
end
assign clk_out = clk_8 | clk_9;
endmodule