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



  1. module clk_div (clk,reset, clk_out);
  2.  
  3. input clk;
  4. input reset;
  5. output clk_out;
  6.  
  7. reg [1:0] r_reg;
  8. wire [1:0] r_nxt;
  9. reg clk_track;
  10.  
  11. always @(posedge clk or posedge reset)
  12.  
  13. begin
  14. if (reset)
  15. begin
  16. r_reg <= 3'b0;
  17. clk_track <= 1'b0;
  18. end
  19.  
  20. else if (r_nxt == 2'b10)
  21. begin
  22. r_reg <= 0;
  23. clk_track <= ~clk_track;
  24. end
  25.  
  26. else
  27. r_reg <= r_nxt;
  28. end
  29.  
  30. assign r_nxt = r_reg+1;
  31. assign clk_out = clk_track;
  32. endmodule
  33.  




Here is the test bench clocktb.v

  1. module clkdiv4_tb;
  2. reg clk,reset;
  3. wire clk_out;
  4.  
  5. clk_div t1(clk,reset,clk_out);
  6. initial
  7. clk= 1'b0;
  8. always
  9. #5 clk=~clk;
  10. initial
  11. begin
  12. #5 reset=1'b1;
  13. #10 reset=1'b0;
  14. #500 $finish;
  15. end
  16.  
  17. initial
  18. $monitor("clk=%b,reset=%b,clk_out=%b",clk,reset,clk_out);
  19.  
  20. initial
  21. begin
  22. $dumpfile("clkdiv4_tb.vcd");
  23. $dumpvars(0,clkdiv4_tb);
  24. end
  25. endmodule
  26.  
  27.  




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.