奇数偶数分频
占空比为50%的分频
偶数分频比较简单
比如N分频,那么计数到N/2-1,然后时钟翻转,代码如下:
1 module even(clk_in,clk_out,rst_n);
2 input clk_in;
3 input rst_n;
4 output clk_out;
5
6 parameter N=6;
7
8 reg [3:0] cnt;
9 reg clk_out;
10
11 always @(posedge clk_in or negedge rst_n) begin
12 if(!rst_n) begin
13 cnt<=4'b0000;
14 clk_out<=0;
15 end
16 else if(cnt==(N/2-1)) begin
17 clk_out<=~clk_out;
18 cnt<=4'b0000;
19 end else cnt<=cnt+1;
20 end
21 endmodule
2 input clk_in;
3 input rst_n;
4 output clk_out;
5
6 parameter N=6;
7
8 reg [3:0] cnt;
9 reg clk_out;
10
11 always @(posedge clk_in or negedge rst_n) begin
12 if(!rst_n) begin
13 cnt<=4'b0000;
14 clk_out<=0;
15 end
16 else if(cnt==(N/2-1)) begin
17 clk_out<=~clk_out;
18 cnt<=4'b0000;
19 end else cnt<=cnt+1;
20 end
21 endmodule
实现奇数分频,分别用上升沿计数到(N-1)/2-1,再计数到N-1,再用下降沿计数到(N-1)/2-1,再计数到N-1,,得到两个波形,然后相或即可 代码如下:
1 module div3(clk,clk_out,rst_n);
2 input clk,rst_n;
3 output clk_out;
4
5 reg [3:0] cnt_p,cnt_n;
6 reg clk_p,clk_n;
7 parameter N=5;
8
9 always @(posedge clk or negedge rst_n) begin
10 if(!rst_n)
11 cnt_p<=4'h0;
12 else if(cnt_p==N-1)
13 cnt_p<=0;
14 else cnt_p<=cnt_p+1;
15 end
16
17 always @(negedge clk or negedge rst_n) begin
18 if(!rst_n)
19 cnt_n<=4'h0;
20 else if(cnt_n==N-1)
21 cnt_n<=0;
22 else cnt_n<=cnt_n+1;
23 end
24
25 always @(posedge clk or negedge rst_n) begin
26 if(!rst_n)
27 clk_p<=1;
28 else if(cnt_p==(N-1)/2-1)
29 clk_p<=~clk_p;
30 else if(cnt_p==(N-1))
31 clk_p<=~clk_p;
32 end
33
34 always @(negedge clk or negedge rst_n) begin
35 if(!rst_n)
36 clk_n<=1;
37 else if(cnt_n==(N-1)/2-1)
38 clk_n<=~clk_n;
39 else if(cnt_n==(N-1))
40 clk_n<=~clk_n;
41 end
42 assign clk_out=clk_n|clk_p;
43 endmodule
2 input clk,rst_n;
3 output clk_out;
4
5 reg [3:0] cnt_p,cnt_n;
6 reg clk_p,clk_n;
7 parameter N=5;
8
9 always @(posedge clk or negedge rst_n) begin
10 if(!rst_n)
11 cnt_p<=4'h0;
12 else if(cnt_p==N-1)
13 cnt_p<=0;
14 else cnt_p<=cnt_p+1;
15 end
16
17 always @(negedge clk or negedge rst_n) begin
18 if(!rst_n)
19 cnt_n<=4'h0;
20 else if(cnt_n==N-1)
21 cnt_n<=0;
22 else cnt_n<=cnt_n+1;
23 end
24
25 always @(posedge clk or negedge rst_n) begin
26 if(!rst_n)
27 clk_p<=1;
28 else if(cnt_p==(N-1)/2-1)
29 clk_p<=~clk_p;
30 else if(cnt_p==(N-1))
31 clk_p<=~clk_p;
32 end
33
34 always @(negedge clk or negedge rst_n) begin
35 if(!rst_n)
36 clk_n<=1;
37 else if(cnt_n==(N-1)/2-1)
38 clk_n<=~clk_n;
39 else if(cnt_n==(N-1))
40 clk_n<=~clk_n;
41 end
42 assign clk_out=clk_n|clk_p;
43 endmodule