Verilog Code for Clock Divider ....If you want to divide the clock by two set parameter N by two and so on. This code will also work for clock division by an odd number.
module clkdivbyn;
reg clk;
reg clk_n;
parameter [3:0] N = 4'h7;
reg [3:0] pos_cnt;
reg [3:0] neg_cnt;
initial
begin
clk = 1'b0;
clk_n = 1'b0;
pos_cnt = 4'b0;
neg_cnt = 4'b0;
#1000 $finish;
end
always
begin
#5 clk = 1'b1;
#5 clk = 1'b0;
end
always @ ( posedge clk )
begin
pos_cnt <= (pos_cnt + 1'b1) % N ;
end
always @ (negedge clk)
begin
neg_cnt <= (neg_cnt + 1'b1) % N ;
end
always @( clk )
begin
if ( (N%2) == 1'b0)
clk_n <= ( pos_cnt >= (N/2)) ? 1'b1 : 1'b0;
else
clk_n <= (( pos_cnt > (N/2)) || ( neg_cnt > (N/2))) ? 1'b1 : 1'b0;
end
endmodule
verilog code, software, classes , EDA tools
module clkdivbyn;
reg clk;
reg clk_n;
parameter [3:0] N = 4'h7;
reg [3:0] pos_cnt;
reg [3:0] neg_cnt;
initial
begin
clk = 1'b0;
clk_n = 1'b0;
pos_cnt = 4'b0;
neg_cnt = 4'b0;
#1000 $finish;
end
always
begin
#5 clk = 1'b1;
#5 clk = 1'b0;
end
always @ ( posedge clk )
begin
pos_cnt <= (pos_cnt + 1'b1) % N ;
end
always @ (negedge clk)
begin
neg_cnt <= (neg_cnt + 1'b1) % N ;
end
always @( clk )
begin
if ( (N%2) == 1'b0)
clk_n <= ( pos_cnt >= (N/2)) ? 1'b1 : 1'b0;
else
clk_n <= (( pos_cnt > (N/2)) || ( neg_cnt > (N/2))) ? 1'b1 : 1'b0;
end
endmodule
verilog code, software, classes , EDA tools