一,产生定时误差的主要原因:
1. 定时器产生溢出中断时,CPU正在执行某指令
2. 定时器产生溢出中断时,CPU正在执行某中断服务程序
二,消除误差的方法:
为了提高精度,可以将THx和TLx从产生溢出到被重新赋值的已有的计数值读出,并补偿到计数值初值中去,可以消除定时/计数器的定时误差。
三,代码:
代码头部加入修正变量
unsigned char fixtime; //定义修正变量
其次,在定时器0中断服务头部加入以下修正代码:
EA=0;//禁止所有中断请求
TR0=0;//关闭T0
fixtime=TL0+0x0B;//将TL0中已计数值写入fixtime,并加上修正操作占用的11个机器周期
TL0=0xF0+fixtime;//将修正值写入TL0
TH0=0xD8+(char)CY;//修正TL0时可能产生进位,要补偿到TH0
EA=0;//允许所有中断请求
TR0=1;//开启TR0