分频器的Verilog实现
写在前面的话:找工作过程中经常遇到的分频类型,在此简单整理,代码亲自验证过,如有问题,烦请告知。
1.偶分频
偶分频比较简单,对于N(N为偶数)分频,只需计数到N/2-1,然后时钟翻转、计数清零,如此循环就可以得到N(偶)分频。
(二分频)
module div_2 (q,clk,rst_n);
input rst_n;
input clk;
output reg q;
always @ (posedge clk or negedge rst_n)begin
if(rst_n==1'b0)
q<=1'b0;
else
q<=~q;
end
endmodule
二分频仿真结果图
(六分频)
module div_6(clk_out,clk,rst_n);
output clk_out;
input clk;
input rst_n;
reg [1:0] cnt;
reg clk_out;
parameter N=6;
always @ (posedge clk or negedge rst_n)begin
if(rst_n==1'b0)
begin
cnt <= 0;
clk_out<= 0;
end
else if(cnt==N/2-1)
begin
clk_out<=~clk_out;
cnt<=0;
end
else
cnt <= cnt + 1'b1;
end
endmodule
六分频仿真结果图
2.奇分频(占空比50%)
实现奇数(N)分频,分别用上升沿计数到(N-1)/2,再计数到N-1;用下降沿计数到(N-1)/2,再计数到N-1,得到两个波形,然后把它们相或即可得到N分频。
(3分频)
module div_3 (q,clk,rst_n);
output q;
input rst_n;
input clk;
reg q1,q2;
reg [1:0] count1,count2;
always@(posedge clk or negedge rst_n)begin
if(rst_n==1'b0)
begin
q1<=1'b0;
count1<=2'b00;
end
else if(count1==0)
begin
q1<=~q1;
count1<=count1+1'b1;
end
else if(count1==1)
begin
q1=~q1;
count1<=count1+1'b1;
end
else
count1<=2'b00;
end
always@(negedge clk or negedge rst_n)begin
if(rst_n==1'b0)
begin
q2<=1'b0;
count2<=2'b00;
end
else if(count2==0)
begin
q2<=~q2;
count2<=count2+1'b1;
end
else if(count2==1'b1)
begin
q2=~q2;
count2<=count2+1'b1;
end
else
count2<=2'b00;
end
assign q=q1|q2;
endmodule
3分频仿真图
(5分频)//5分频原理与3分频一样,只不过代码设计上简化了一点,不影响结果。
module test(
input clk,
input rst_n,
output q
);
reg [2:0] cnt;
reg q1, q2;
always@(posedge clk or negedge rst_n) begin
if(~rst_n) begin
cnt <= 0;
end
else if(cnt <3'd4) begin
cnt <= cnt + 1'b1;
end
else
cnt <= 0;
end
always@(posedge clk or negedge rst_n) begin
if(~rst_n) begin
q1 <= 1'b1;
end
else if(cnt == 3'd1) begin
q1 <= ~q1;
end
else if(cnt == 3'd4) begin
q1 <= ~q1;
end
else q1 <= q1;
end
always@(negedge clk or negedge rst_n) begin
if(~rst_n) begin
q2 <= 1'b1;
end
else q2 <= q1;
end
assign q = q1 | q2;
endmodule
5分频仿真结果图
3.占空比不为50%
在此拿三分频举例,分别给出1/3、2/3占空比例子。对于任意占空比首先要知道占空比是高电平与周期之比,然后通过计数产生高电平个数、取反,再计数到N-1取反,计数器置零。
(1)占空比2/3
module div3(clk,rst_n,q);
input clk;
input rst_n;
output reg q;
reg [1:0] cnt;
always@(posedge clk or negedge rst_n)begin
if(rst_n==1'b0)
begin
cnt<=2'd0;
q<=0;
end
else if(cnt==2'd0)
begin
q<=~q;
cnt<=cnt+1'b1;
end
else if(cnt==2'd2)
begin
q<=~q;
cnt<=2'd0;
end
else begin
q<=q;
cnt<=cnt+1'b1;
end
end
endmodule
占空比2/3仿真图
(2)占空比1/3
module div3(clk,rst_n,q);
input clk;
input rst_n;
output reg q;
reg [1:0] cnt;
always@(posedge clk or negedge rst_n)begin
if(rst_n==1'b0)
begin
cnt<=2'd0;
q<=0;
end
else if(cnt==2'd1)//代码仅此处计数值不同
begin
q<=~q;
cnt<=cnt+1'b1;
end
else if(cnt==2'd2)
begin
q<=~q;
cnt<=2'd0;
end
else begin
q<=q;
cnt<=cnt+1'b1;
end
end
endmodule
占空比1/3
通过以上1/3、2/3可以知道对于其余不同占空比N分频应该可以有所理解。