//function: randome divider clk_out= clk/k1
//note
// k1: must bigger than 1 (>=2)
// div_change_en: enable signal for change the k1
module clock_div(
//input
clk, //input clk
rstn,
k1, //counter value
//output
k1_clk,
change_clk_en
);
parameter DIV_WIDTH=5;
//***********************************************************************
//input output
input [DIV_WIDTH-1:0] k1; //input divider value
input clk;
input rstn;
output k1_clk;
output change_clk_en;
wire [DIV_WIDTH-1:0] k1_sync;
wire [DIV_WIDTH-1:0] k1_sync_dec;
reg [DIV_WIDTH-1:0] k1_cnt;
reg k1_clk;
// -----------------------------------------------------------------------------
// k1,k1_cnt,k1_clk random divider
// -----------------------------------------------------------------------------
assign k1_sync = k1;
assign k1_sync_dec = k1 -1'b1;
// -----------------------------------------------------------------------------
// k1_cnt
// -----------------------------------------------------------------------------
always @(posedge clk or negedge rstn)
begin
if(~rstn)
k1_cnt <= #0 0;
else if((k1_cnt < k1_sync_dec ))
k1_cnt <= #0 k1_cnt + 1;
else
k1_cnt <= #0 0;
end
// -----------------------------------------------------------------------------
// k1_clk
// -----------------------------------------------------------------------------
//*****Special Notes ********
//***Use "=" in the always is only for simulation
//** the "clk" will generate the clock signal "k1_clk" and data signal
//** it is only that the generated data signal can be adopted right by "k1_clk"
//** it has not effect on Synthesis implementation
//***********
always @(posedge clk or negedge rstn)
begin
if(~rstn)
k1_clk = 1'b1;
else if(k1_cnt == (k1[DIV_WIDTH-1:1] - 1))
k1_clk = 1'b0;
else if(k1_cnt == (k1_sync_dec))
k1_clk = 1'b1;
else
k1_clk = k1_clk;
end
//change enable signal for divider change valule
//clk_out enable:
//******Special Note: need add #1 delay when the before register add delay
//for simulation
//assign #2 change_clk_en = (k1_cnt == (k1_sync_dec));
assign change_clk_en = (k1_cnt == (k1_sync_dec));
endmodule