static int delayLoopCount = FCLK/10000/10;
void delay(int nTime)
{
// time=0: adjust the Delay function by WatchDog timer.
// time>0: the number of loop time
// resolution of time is 100us.
int i,adjust=0;
if(nTime==0)
{
nTime = 200;
adjust = 1;
delayLoopCount = 400;
//PCLK/1M,Watch-dog disable,1/64,interrupt disable,reset disable
WTCON = ((PCLK/1000000-1)<<8)|(2<<3); //看門狗定時器的預分頻值設置爲 PCLK/1000000 分頻值 爲64
WTDAT = 0xffff; //for first update
WTCNT = 0xffff; //resolution=64us @any PCLK 所以一個週期的時間是 64/1000000 s 即爲64us
//肯能誤解的是這裏conut值是遞減的但是減一次就是64us 即到0xfffe時候 所以dat來補充的時候過了 ffff×64us時間還是很長的
WTCON = ((PCLK/1000000-1)<<8)|(2<<3)|(1<<5); //Watch-dog timer start 打開
}
for(;nTime>0;nTime--)
for(i=0;i<delayLoopCount;i++); //測量80000個時鐘週期內有幾個64us ,但是貌似還是不是很精確,因爲最後一個在64us中間的情況好像沒有考慮
if(adjust==1)
{
WTCON = ((PCLK/1000000-1)<<8)|(2<<3); //Watch-dog timer stop
i = 0xffff - WTCNT; //1count->64us, 200*400 cycle runtime = 64*i us 測試結果給i這裏僅僅只是第一次的效果,以後不會再有了
delayLoopCount = 8000000/(i*64); //200*400:64*i=1*x:100 -> x=80000*100/(64*i) 同上
}
/*
1
最終以後調用 每次使用的只有 ntime × delayloopcount × -------------
PCLK
1
可以有等式 80000 × ----------- = i × 64 us
pclk
所以你想要的是 ntime = 1 的時候 下面式子相等
1
ntime × delayloopcount × ------------- = 1us
PCLK
8000000
現在就開始假設了 delayloopcount = ------------------
1
80000 ×---------
pclk
8000000
帶入上面看你得到了什麼 1× -------------------------- = 1
8000000
*/
}