Frequency divisor in verilog

Guilherme Stéfano picture Guilherme Stéfano · Jun 3, 2014 · Viewed 10k times · Source

i need a frequency divider in verilog, and i made the code below. It works, but i want to know if is the best solution, thanks!

module frquency_divider_by2 ( clk ,clk3 );
output clk3 ;
reg clk2, clk3 ;
input clk ;
wire clk ;
initial clk2 = 0;
initial clk3 = 0;
 always @ (posedge (clk)) begin
   clk2 <= ~clk2;
 end
 always @ (posedge (clk2)) begin
  clk3 <= ~clk3;
 end
endmodule

the circuit generated by quartus:

enter image description here

Answer

Morgan picture Morgan · Jun 4, 2014

Your block divides the frequency by 4 not 2. There is actually quite a good description of this on Wikipedia Digital Dividers. Your code can be tidied up a bit but only 1 D-Type is required, which is smaller than a JK Flip-flop so is optimal.

module frquency_divider_by2(
  input      rst_n,
  input      clk_rx,
  output reg clk_tx
);

always @ (posedge clk_rx) begin
  if (~rst_n) begin
    clk_tx <= 1'b0;
  end
  else begin
    clk_tx <= ~clk_tx;
  end
end

endmodule

When chaining these types of clock dividers together be aware that there is a clk to q latency which is compounded every time you go through one of these dividers. IF this is not managed correctly by synthesis the clocks can not be considered synchronous.

Example on EDAplayground, should open the waveform when run.