简体   繁体   中英

clock division in two in verilog

I am trying to divide the input clock by two; the output clock should be half the frequency of the input clock.

module clk_div(in_clk, out_clk, rst);
  input  in_clk;
  input  rst;
  output out_clk;
  reg    out_clk;

always @(posedge in_clk) begin
  if (!rst) begin
    out_clk <= 1'b0;
  end
  else 
    out_clk <= ~out_clk;
end
endmodule

The testbench is:

module dd;
  // Inputs
  reg clk_in;
  reg reset;

  // Outputs
  wire clk_out;

  // Instantiate the Unit Under Test (UUT)
  clk_div uut (
    .clk_in(clk_in), 
    .reset(reset), 
    .clk_out(clk_out)
  );

  always #10 clk_in =~clk_in ;

  initial begin
    // Initialize Inputs
    clk_in = 0;
    reset  = 0;
    #100;
    reset  = 1;
  end   
endmodule

The output waveform shows only the input clock being generated. No matter what I try, the output clock waveform would not come. Is this code correct for clock division by two?

You need to change the port names in your instance. Change your instance to:

clk_div uut (
    .in_clk(clk_in), 
    .rst(reset), 
    .out_clk(clk_out)
);

I get a divide-by-2 with this fix.

Your code had compile errors on 2 simulators for me.

I think the problem is that you need to use the logical negation operator ( ! ) rather than the bitwise negation operator ( ~ ). See info here .

For a complete, verified example of dividing a clock by 2, see here .

i use the following code for clock dividers.Just change the parameter and get the desired outputs...

 module clk_div(
                clk,
                rst,
                count);

parameter count_width=27;
parameter count_max=25000000;

output [count_width-1:0] count;
reg [count_width-1:0] count;
input clk,rst;


initial
count<=0;

always@(posedge clk)
if(rst)
begin
    count=0;
end


else 
begin
if (count<count_max-1)
begin
    count<=count+1;
end


else if (count==count_max)
begin
    count <=~count;
end


else if (count>count_max)
begin
    count<=0;
end
end
endmodule

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM