|
这是一个IIC电调上的一个延时程序,小弟有一个疑问不接。这个延时的原理是,在当前计数器值 CountMilliseconds 的基础上加上要延时的w得到新的计数值w,将新的w和 CountMilliseconds相减,当定时器计数器 CountMilliseconds 增加到w时,他们的差值为0,。当 CountMilliseconds 在增加1时,差值应该为FFFF,此时 CheckDelay(unsigned int t)函数将返回1,表明定时到。这也是为什么SetDelay(unsigned int t)函数要减一。但是我小弟疑问的是当通过SetDelay(unsigned int t)设定了新的值,CountMilliseconds发生了溢出怎么办,也就是它回到了零,这个时候CheckDelay(unsigned int t)检测时岂不要多跑一个周期?
volatile unsigned int CountMilliseconds = 0; //毫秒计数
volatile unsigned char Timer0Overflow; //T/C0 溢出
enum {
STOP = 0,
CK = 1,
CK8 = 2,
CK64 = 3,
CK256 = 4,
CK1024 = 5,
T0_FALLING_EDGE = 6,
T0_RISING_EDGE = 7
};
SIGNAL(SIG_OVERFLOW0)
{
static unsigned char cnt;
Timer0Overflow++;
if(!cnt--)
{
cnt = 3;
CountMilliseconds += 1;
if(I2C_Timeout) I2C_Timeout--;
//if(PPM_Timeout) PPM_Timeout--;
if(SIO_Timeout) SIO_Timeout--;
}
}
void Timer0_Init(void)
{
TCCR0 = TIMER_TEILER; //8分频
// TCNT0 = -TIMER_RELOAD_VALUE; // reload
TIM0_START;
TIMER2_INT_ENABLE;
}
unsigned int SetDelay(unsigned int t)
{
return(CountMilliseconds + t - 1);
}
char CheckDelay (unsigned int t)//
{
return(((t - CountMilliseconds) & 0x8000) >> 8);
}
void Delay_ms(unsigned int w)
{
unsigned int akt;
akt = SetDelay(w);
while (!CheckDelay(akt));
}
|
阿莫论坛20周年了!感谢大家的支持与爱护!!
知道什么是神吗?其实神本来也是人,只不过神做了人做不到的事情 所以才成了神。 (头文字D, 杜汶泽)
|