//******************************************************************************* //程 序 名:高精度时钟 //设 计 者:石鱼WLEEN //设计说明:设置TMR0预分频系数为16,一次计数中断溢出时间为4096us(0x1000) // 每次TMR0中断服务中对时间累计变量microsecond加上4096 // 程序主循环中不停地查询变量microsecond,看是否超过50ms,如果时间超过 // 50ms,则microsecond=microsecond-50000,同时50ms计数器ms50加1 // 基于50ms计数器的累加值,更新秒,分和小时值 // 虽然每一个50ms的变化时间略有偏差,但所有偏差值都保留在microsecond // 中,并得到累计修正,所以长时间跨度计时精确 //******************************************************************************* #include
//*******************//variable define//**********************************
long int microsecond; //microsecond accumulative unit int ms50; //50ms counter int second; //second counter int minute; //minute counter int hour; //hour counter
main() {
//*******************//initialize//************************************** T0CS=0; //timer0 work at timer mode T0IF=0; //clear timer0 flag PSA=0; PS2=1; PS1=0; PS0=0; //psa=0,ps2:ps0=100,1:16 prescale value T0IE=1; //timer0 overflow interrupt enable GIE=1; // global interrupt enable
//*******************//main loop//************************************** while(1) { CLRWDT(); //clear the watchdog T0IE=0; //temporarily forbid the timer0 to interrupt //to keep the value of microsecond
microsecond-=50000; if(microsecond>=50000) //deal with microsecond>=50000 { ms50=+1; //50ms counter increase 1 if(ms50!=20) T0IE=1; //the time is not one second, resume t0ie ms50=0; //the time is one second,clear ms50 second++; //second counter if(second!=60) T0IE=1; //the time is not one minute, resume t0ie second=0; //the time is one minute,clear second minute++; //minute counter if(minute!=60) T0IE=1; //the time is not one hour, resume t0ie minute=0; //the time is one hour,clear minute hour++; //hour counter if(hour!=24) T0IE=1; //the time is not 24h, resume t0ie hour=0; //the time is 24 hour,clear hour } else microsecond+=50000; T0IE=1; //resume t0ie } }
void interrupt timer(void) { microsecond+=4096; }