循环等待定时器中断后,累加次数只要一多,时间就不准,这是为什么?
时间:10-02
整理:3721RD
点击:
HI,ALL 本来是红外发射码,但是发现只要定时器用得多了,就有问题,只能将代码一点一点删除,现在就剩下发38K脉冲持续500次,延时一段时间,再循环。实测38K持续时间忽长忽短,不知所以,请大侠解释一下。
#include <reg51.h>
//#include <C51_ZY.h>
sbit P1_1=P1^1; // LED
static bit OP; //the turn on or off of the IR led
sbit P1_3=P1^3; // IR pin
static unsigned char flag; //the flag of IR emission
static unsigned int lead_high;
static unsigned int lead_low;
static unsigned int count; //delay count
static unsigned int endcount; //terminate count
void SendIRdata(void);
void timer0_int(void);
void IR_transfer_test(void);
void delay_100ms(int);
void main(void)
{
IE=0x0;
P1_1=0;
//AUXR |= 0x80; //SET TIMER0 1T MODE
P1M1 &= 0xF7;
P1M0 |= 0x08; //SET P1_3 PUSH-PULL MODE
timer0_int();
IR_transfer_test();
}
void IR_transfer_test()
{
//int i;
// int j;
count=0;
flag=0;
OP=0;
P1_3=0;
lead_high=500;
lead_low=500;
do{
EA=1;
SendIRdata();
EA=0;
P1_3=0;
delay_100ms(1);
} while(1);
}
void SendIRdata()
{
endcount=lead_high;
flag=1;
count=0;
//ET0=1;TR0 = 1;
do{}while(count<endcount);
//TR0 = 0;ET0=0;
//endcount=lead_low;
//flag=0;
// count=0;
//ET0=1;TR0 = 1;
//do{}while(count<endcount);
// TR0 = 0;ET0=0;
}
void timer0_int()
{
EA=1;
AUXR |= 0x80; //定时器时钟1T模式
TMOD &= 0xF0; //设置定时器模式
TMOD |= 0x02; //设置定时器模式
TL0 = 0x64; //设置定时初值
TH0 = 0x64; //设置定时重载值
TF0 = 0; //清除TF0标志
ET0=1;
TR0 = 1; //定时器0开始计时
}
void timeint(void) interrupt 1
{
count++;
if (flag==1)
{
OP=~OP;
}
else
{
OP = 0;
}
P1_3 = OP;
}
void delay_100ms(int k)
{
int i,j;
for(k;k>0;k--)
{
for(i=0;i<150;i++)
{
for(j=0;j<100;j++);
}
}
}
#include <reg51.h>
//#include <C51_ZY.h>
sbit P1_1=P1^1; // LED
static bit OP; //the turn on or off of the IR led
sbit P1_3=P1^3; // IR pin
static unsigned char flag; //the flag of IR emission
static unsigned int lead_high;
static unsigned int lead_low;
static unsigned int count; //delay count
static unsigned int endcount; //terminate count
void SendIRdata(void);
void timer0_int(void);
void IR_transfer_test(void);
void delay_100ms(int);
void main(void)
{
IE=0x0;
P1_1=0;
//AUXR |= 0x80; //SET TIMER0 1T MODE
P1M1 &= 0xF7;
P1M0 |= 0x08; //SET P1_3 PUSH-PULL MODE
timer0_int();
IR_transfer_test();
}
void IR_transfer_test()
{
//int i;
// int j;
count=0;
flag=0;
OP=0;
P1_3=0;
lead_high=500;
lead_low=500;
do{
EA=1;
SendIRdata();
EA=0;
P1_3=0;
delay_100ms(1);
} while(1);
}
void SendIRdata()
{
endcount=lead_high;
flag=1;
count=0;
//ET0=1;TR0 = 1;
do{}while(count<endcount);
//TR0 = 0;ET0=0;
//endcount=lead_low;
//flag=0;
// count=0;
//ET0=1;TR0 = 1;
//do{}while(count<endcount);
// TR0 = 0;ET0=0;
}
void timer0_int()
{
EA=1;
AUXR |= 0x80; //定时器时钟1T模式
TMOD &= 0xF0; //设置定时器模式
TMOD |= 0x02; //设置定时器模式
TL0 = 0x64; //设置定时初值
TH0 = 0x64; //设置定时重载值
TF0 = 0; //清除TF0标志
ET0=1;
TR0 = 1; //定时器0开始计时
}
void timeint(void) interrupt 1
{
count++;
if (flag==1)
{
OP=~OP;
}
else
{
OP = 0;
}
P1_3 = OP;
}
void delay_100ms(int k)
{
int i,j;
for(k;k>0;k--)
{
for(i=0;i<150;i++)
{
for(j=0;j<100;j++);
}
}
}
因为定时器的初始值有误差,造成累加越多,误差越大,所以就不准了
看不懂.。