前几天用STC89C52单片机制作了一个电子时钟,经过一段时间的实验,发现时间精度存在误差,一分钟慢4秒左右。
这可了不得,十分钟就要慢40秒,一天下来不得慢半96分钟!!!
这个单片机晶振频率为11.0592mhz,和大部分时钟的晶振频率相同,应该没有问题。
后天考虑到源代码:
在定时器中断函数里:
void t0(void) interrupt 1 using 0
{
tcount++;
if(tcount==4000)
{tcount=0;
second++;
if(second==60)
{second=0;
minute++;
if(minute==60)
{minute=0;
hour++;
if(hour==24)
{hour=0;
}
}
}
P1=~P1;
}
}
interrupt 后面的数字简单的说就是中断服务函数的代号
0代表外中断0
1代表定时计数器0中断
2代表外中断1
3代表定时计数器1中断
4代表串行口中断
所以interrupt 1代表定时计数器产生中断后就转到这个函数里面执行。
代码其实还挺简单,每中断4000下将产生1秒。
等等...
每4000下的中断为1秒,那么原因很有可能在这里。
试着将tcount==3600,和秒表对比发现竟然每一分钟快了1秒左右。
bingo!问题的确出在tcount的取值上面,将tcount的数值改为3700,和秒表对比发现,秒数没有误差,有误差的应该就是毫秒级吧。
void t0(void) interrupt 1 using 0
{
tcount++;
if(tcount==3700)
{tcount=0;
second++;
if(second==60)
{second=0;
minute++;
if(minute==60)
{minute=0;
hour++;
if(hour==24)
{hour=0;
}
}
}
P1=~P1;
}
}
这样就解决了时钟精度的问题。
相关文章









