## Verilog Examples - Clock Divide by 4

Our previous example of cock divide by 2 seemed trivial, so let us extend it to make a divide by 4.So for example if the frequency of the clock input is 50 MHz, the frequency of the output will be 12.5 MHz. In other words the time period of the outout clock will be 4 times the time perioud of the clock input.

The figure shows the example of a clock divider.

Problem - Write verilog code that has a clock and a reset as input. It has an output that can be called out_clk. The out_clk is also a clock that has a frequency one forth the frequency of the input clock. It has synchronous reset and if there if the reset is 1, the output clock resets to 0. Write test bench to verify it.

Solution -

This is the main code clock.v

 `module clk_div (clk,reset, clk_out); input clk;input reset;output clk_out; reg [1:0] r_reg;wire [1:0] r_nxt;reg clk_track; always @(posedge clk or posedge reset) begin if (reset) begin r_reg <= 3'b0; clk_track <= 1'b0; end  else if (r_nxt == 2'b10) begin r_reg <= 0; clk_track <= ~clk_track; end  else r_reg <= r_nxt;end  assign r_nxt = r_reg+1; assign clk_out = clk_track;endmodule `

Here is the test bench clocktb.v

 ` module clkdiv4_tb; reg clk,reset; wire clk_out;  clk_div t1(clk,reset,clk_out); initial clk= 1'b0; always #5 clk=~clk; initial begin #5 reset=1'b1; #10 reset=1'b0; #500 \$finish; end  initial \$monitor("clk=%b,reset=%b,clk_out=%b",clk,reset,clk_out);  initial begin \$dumpfile("clkdiv4_tb.vcd"); \$dumpvars(0,clkdiv4_tb); end endmodule  `

Explanation

The counter r_nxt counts to 2 and then becomes 0.

 ```if (r_nxt == 2'b10) begin r_reg <= 0;```

Rest of the code is simple to understand. In the next example we will write a code for divide the clock by any even Number.