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
*/
}