# Verilog语言实现2分频、3分频、4分频、8分频+产生指定频率的时钟周期

### 1.一个计数器就可以搞定：偶数次分频

//第一种四分频、八分频写法
reg [1:0] div_cnt1;
always@(posedge clk_i or negedge rst_n_i)
begin
if(!rst_n_i)
div_cnt1<=2'b00;
else
div_cnt1<=div_cnt1+1'b1;
end

always@(posedge clk_i or negedge rst_n_i)  //四分频
begin                                      //计数器放在外面 来实现计数   div_cnt1
if(!rst_n_i)                           //00 01 10 11 捕捉00和10 实现四分频
div4_o_r<=1'b0;
else if(div_cnt1==2'b00 || div_cnt1==2'b10)
div4_o_r<=~div4_o_r;
else
div4_o_r<=div4_o_r;
end

always@(posedge clk_i or negedge rst_n_i)  //八分频
begin                                      //基于同一个计数器实现计数  注意比较方式
if(!rst_n_i)                           //00 01 10 11 捕捉11  实现8分频
div8_o_r<=1'b0;
else if((~div_cnt1[0]) && (~div_cnt1[1]))   //两个&&是逻辑运算
div8_o_r<=~div8_o_r;
else
div8_o_r<=div8_o_r;
end

//第二种四分频八分频的写法
reg counter_4;
reg [1:0] counter_8;

always @(posedge clk_i or negedge ngrst_i) begin
if(~ngrst_i) begin
counter_4 <= 0;
div4_o = 0;
end else if(counter_4 == 1) begin
counter_4 <= 0;
div4_o <= ~div4_o;
end else if(counter_4 == 0) begin
counter_4 <= counter_4 + 1;
end
end

always @(posedge clk_i or negedge ngrst_i) begin
if(~ngrst_i) begin
counter_8 <= 0;
div8_o = 0;
end else if(counter_8 == 3) begin
counter_8 <= 0;
div8_o <= ~div8_o;
end else begin
counter_8 <= counter_8 + 1;
end
end

reg div2_o_r; //二分频电路实际上不需要过于复杂 不需要计数器进行计数
always@(posedge clk_i or negedge rst_n_i)
begin
if(!rst_n_i)
div2_o_r<=1'b0;
else
div2_o_r<=~div2_o_r;
end

### 2.需要多个计数器搞定：奇数次分频

//三分频电路的实现

reg [1:0] pos_cnt;  //上升沿计数
reg [1:0] neg_cnt;  //下降沿计数

always@(posedge clk or negedge rst_n)  //上升沿;复位清零;计到2清零
begin
if(!rst_n)
pos_cnt<=2'b00;
else if(pos_cnt==2'd2)
pos_cnt<=2'b00;
else
pos_cnt<=pos_cnt+1'b1;
end

always@(negedge clk or negedge rst_n)  //下降沿;复位清零;计到2清零
begin
if(!rst_n)
neg_cnt<=2'b00;
else if(neg_cnt==2'd2)
neg_cnt<=2'b00;
else
neg_cnt<=neg_cnt+1'b1;
end

reg div3_o_r0;
reg div3_o_r1;

always@(posedge clk or negedge rst_n)
begin
if(!rst_n)
div3_o_r0<=1'b0;
else if(pos_cnt<2'd1)
div3_o_r0<=1'b1;
else
div3_o_r0<=1'b0;
end

always@(negedge clk or negedge rst_n)
begin
if(!rst_n)
div3_o_r1<=1'b0;
else if(neg_cnt<2'd1)
div3_o_r1<=1'b1;
else
div3_o_r1<=1'b0;
end

assign div3_o=div3_o_r0 | div3_o_r1;

reg [2:0] counter_3;

always @(posedge clk_i or negedge ngrst_i or negedge clk_i) begin
if(~ngrst_i) begin
counter_3 <= 0;
div3_o = 0;
end else if(counter_3 == 2) begin
counter_3 <= 0;
div3_o <= ~div3_o;
end else begin
counter_3 <= counter_3 + 1;
end
end

### 3.FPGA的时钟频率为50MHz，产生频率2hz的时钟

1/50M = 0.02 * 10^(-6) s = 20ns

1/2 = 0.5s = 0.5 * 10^9 ns = 5 * 10^8 ns

(5 * 10^8 ns) / 20 = 2500_0000

reg [25:0] div2hz_cnt;

always@(posedge clk_i or negedge rst_n_i)
begin
if(!rst_n_i)
div2hz_o_r<=0;
else if(div2hz_cnt==26'd12_499999 || div2hz_cnt==26'd24_999999)
div2hz_o_r<=~div2hz_o_r;
else
div2hz_o_r<=div2hz_o_r;
end

06-04 1万+
03-16 4685
07-23 4312
10-03
05-28
09-05 2万+
10-20
06-11 2万+
06-13 6474
08-31 3万+
12-12 4059
10-16
10-06