void IntToStr(unsigned int t, unsigned char *str, unsigned char n)
{
unsigned char a[5]; char i, j;
a[0]=(t/10000)%10; //取得整数值到数组
a[1]=(t/1000)%10;
a[2]=(t/100)%10;
a[3]=(t/10)%10;
a[4]=(t/1)%10;
for(i=0; i<5; i++) //转成ASCII码
a=a+'0';
for(i=0; a=='0' && i<=3; i++);
for(j=5-n; j<i; j++) //填充空格
{ *str=' '; str++; }
for(; i<5; i++)
{ *str=a; str++; } //加入有效的数字
*str='\0';
}
//count interrupt
void t0(void) interrupt 1 using 0
{
T0count++;
TH0=0;
TL0=0;
}
//time interrupt
void t1(void) interrupt 3 using 0
{
TH1=0x5d;
TL1=0x3d;
timecount++;
if(timecount==40) //1秒
flag=1;
}
main()
{
unsigned char i;
init();
while(1)
{
if(flag==1) //如果定时时间到了1s
{
flag=0; //标志位清零
x=T0count*65536+TH0*256+TL0; //获得整型的频率值,T0count计数器在1s内溢出的次数,每溢出一次就计数了T0count*65536次 _ // 再加上当前计数寄存器的值即为实际计数总数
IntToStr(x, &TempBuffer[0], 5);
while(TempBuffer != '\0')
{
write_date(TempBuffer);
i++;
delay(200); //延时200ms
}
write_com(0x80+0x48);
timecount=0;
T0count=0;
TH0=0;
TL0=0;
TR0=1;
TR1=1;
i = 0;
}
}
}
这个是我写的一个关于51单片机的一个计数器程序。
最高可以计数到65536,但是到1KHz或者更大的时候有误差100多,当频率越高误差越大。
请问一下各位,这个误差是出在哪些地方的,通过改进哪里可以提高误差的,希望高手能指点一下
谢谢了
|