`timescale 1ns / 1ps
`define f0 10000000 // f0 = 10MHz
`define K 8 //
`define M 26 // M = 2K for JK PD and M = 4K for EXOR PD
`define N 16 // M = 2N and Nmin = 3M/2K
`define high 1'b1
`define low 1'b0
//TOP Module
module adpll(u1, idclk, kclk, u2);
input u1, idclk, kclk;
output u2;
//Instantiating JK Phase Detector
JKPD jkpd1(u1, u2, q);
//Instantiating K Counter Loop Filter
LF lf1(q, kclk, carry, borrow);
//Instantiating DCO
DCO dco1(carry, borrow, idclk, idout);
//Instantiating Modulo N Counter
NC nc1(idout, u2);
endmodule
//JK Phase Detector
module JKPD (u1, u2, q);
input u1, u2;
output q;
wire q, q_b;
//JK Phase Detector Logic
nor nor1(q_b, u1, q);
nor nor2(q, u2, q_b);
endmodule
//K Counter Loop Filter
module LF (q, kclk, carry, borrow);
input q, kclk;
output carry, borrow;
reg carry, borrow;
integer kup, kdn;
initial
begin
kup=0;
kdn=0;
end
//K Counter Logic
always @(negedge kclk)
begin
if (!q)
begin
kdn <= kdn+1;
if (kdn == (`K))
kdn <= `low;
if (kdn >=(`K/2))
borrow <= `high;
else borrow <= `low;
end
else if (q)
begin
kup <= kup+1;
if (kup == (`K))
kdn <= `low;
if (kup >=(`K/2))
carry <= `high;
else carry <= `low;
end
end
endmodule
//Increment Decrement Counter DCO
module DCO (carry, borrow, idclk, idout);
input carry, borrow, idclk;
output idout;
reg toggle = `low, delay=`low, c2_delay = `low, c4_delay = `low;
reg c_check =`low, b_check=`low;
integer d_counter = 0;
//ID Counter Logic
//condition 1
wire c11, c12, c1;
nor(c11, borrow, carry);
and(c12, carry, borrow, c_check, b_check);
or g1(c1, c11, c12);
//condtition 2
wire c2;
and g2(c2, (~toggle), (~c_check), carry);
//condition 3
wire c3;
and g3(c3, carry , toggle, (~c_check));
//condition 4
wire c4;
and g4(c4, toggle, borrow, (~b_check));
//condition 5
wire c5;
and g5(c5, (~toggle), (~b_check), borrow);
//logic for toggle
always @(posedge idclk)
begin
if(!carry) c_check = `low;
if(!borrow) b_check = `low;
if (delay)
begin
d_counter = d_counter-1;
if (d_counter == 0)
delay = `low;
end
else if(c2_delay)
begin
toggle = `low;
delay = `high;
d_counter = 2;
c2_delay = `low;
end
else if(c4_delay)
begin
toggle = `high;
delay = `high;
d_counter = 2;
c4_delay = `low;
end
else if (c1)
toggle = ~toggle;
else if (c2)
begin
toggle = `high;
c_check = `high;
delay = `high;
d_counter = 1;
c2_delay = `high;
end
else if (c3)
begin
c_check = `high;
toggle = `low;
delay = `high;
d_counter = 2;
end
else if(c4)
begin
b_check = `high;
toggle = `low;
delay = `high;
d_counter = 1;
c4_delay = `high;
end
else if(c5)
begin
b_check = `high;
toggle = `high;
delay = `high;
d_counter = 2;
end
end
//ID Counter Output
and and1(idout,(~idclk),(~toggle));// idout = (idclk) & (toggle);
endmodule
//Modulo N Counter
module NC (idout, u2);
input idout;
output u2;
endmodule