SPIRO THE TECH GURU

Back

Verilog Examples - Clock Divide by 2

By Admin on

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 output clock will be 4 times the time period 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
SPIRO Google Plus