奇偶分频电路verilog代码
1.偶数分频器
偶数分频器只要在计数器为N/2-1时反转输出就行
//4分频器
module clk_div(
input clk,
input rst_n,
output reg clk_div4
);
reg [3:0]count;
parameter N=4;//若用integer i 采用
always@(posedge clk or negedge rst_n)begin
if(rst_n)
begin
count <=4'b0;
end
else if(count==4'b1)
begin
count <=4'b0;
end
else begin
count <=count +4'd1;
end
end
always @(posedge clk or negedge rst_n)begin
if(rst_n)begin
clk_div4 <=1'b0;
end
else if(count==4'b1)begin
clk_div4<=~clk_div4;
end
else begin
clk_div4<=clk_div4;
end
end
endmodule

2.奇数分频器
奇数分频器有两种,一种是占空比为50的一种是占空比非20的。
首先是占空比非50的,用错位异或实现
module div5(
input clk,
input rst_n,
output clk_div5
);
reg clk1;
reg clk2;
reg [2:0] count;
always @(posedge clk or negedge rst_n) begin
if(rst_n)begin
count <=3'd0;
end
else if(count==3'd4)begin
count <=3'd0;
end
else begin
count <=count+1'b1;
end
end
always @(posedge clk or negedge rst_n) begin
if(rst_n)begin
clk1<=1'b0;
end
else if(count==3'd4)begin
clk1 <=~clk1;
end
else begin
clk1<=clk1;
end
end
always @(posedge clk or negedge rst_n) begin
if(rst_n)begin
clk2<=1'b0;
end
else if(count==3'd2)begin
clk2 <=~clk2;
end
else begin
clk2<=clk2;
end
end
assign clk_div5 = clk2^clk1 ;
endmodule

关键是第一个clk等计数器=N-1跳,第二个在(N-1)/2跳
接下来是50占空比的,用另一个下降沿实现
module top(
input clk,
input rst_n,
output clk_div
);
reg clk1;
reg clk2;
reg [2:0] count;
always @(posedge clk or negedge rst_n) begin
if(rst_n)begin
clk1 <=1'd0;
end
else if(count==3'd0)begin
clk1 <=1'd1;
end
else if(count==3'd2)begin
clk1 <=1'b0;
end
end
always @(posedge clk or negedge rst_n) begin
if(rst_n)begin
count <=3'd0;
end
else if(count==3'd4)begin
count <=3'd0;
end
else begin
count <=count+1'b1;
end
end
always @(negedge clk or negedge rst_n) begin
if(rst_n)begin
clk2<=1'b0;
end
else begin
clk2<=clk1;
end
end
assign clk_div = clk2 || clk1 ;
endmodule
关键在第一个于(N-1)/2的时候从1跳0,第二个下降沿触发,相当于第一个的后一级寄存器。
