在下用此单片机测量美新温度传感器SMT16030输出的方波的占空比,老是出问题,方波的频率是1khz到4khz,测量第一个下降沿的数值比第二个下降沿的数值还大,而且都不对,
程序如下
#include
#include
sbit pwmin=P1^1;
sbit P20=P2^0;
sbit P21=P2^1;
sbit P22=P2^2;
sbit P23=P2^3;
sbit P24=P2^4;
sbit P32=P3^2;
float down1=0,down2=0,up=0;
unsigned char finish;
unsigned int th2=0,tl2=0;
char putchar(char ch)
{
SBUF=ch;
while(!TI);
TI=0;
return ch;
}
void TIM2_Init()
{
T2CON=0X09;
TH0=0;
TL0=0;
RCAP2L=0;
RCAP2H=0;
T2MOD=0;
ET2=1;
}
void USART_Init()
{
TMOD = 0x20;
SCON = 0x50;
TH1 = 0xFD;
TL1 = 0xFD;
TR1 = 1;
}
void delay(unsigned char x)
{
unsigned char a,b;
for(a=0;a
for(b=0;b<100;b++);
}
void test()
{
float pwm,temperature;
finish=0;
TR2=1;
ET2=1;
while(finish==0);
pwm=((float)(down2-up))/(down2-down1);
temperature=(pwm-0.32)/0.0047;
printf("%f\r\n",temperature);
}
void main()
{
TIM2_Init();
USART_Init();
EA=1;
ET2=1;
TR2=1;
while(1)
{
if(P32==0)
{
delay(10);
if(P32==0)
test();
while(!P32);
}
//test();
}
}
void time2() interrupt 5
{
static unsigned char flag=0;
if(TF2==1)
{
TF2=0;
P20=~P20;
}
if(EXF2==1)
{
EXF2=0;
th2= RCAP2H;
tl2= RCAP2L;
//down1=(th2*256)+tl2;
P21=~P21;
printf("高八位=%d\r\n",th2);
printf("低八位=%d\r\n",tl2);
//printf("down1=%f\r\n",down1);
switch (flag)
{
case 0:
// printf("高八位=%d\r\n",th2);
// printf("低八位=%d\r\n",tl2);
down1=(th2*256+tl2);
P21=~P21;
printf("down1=%f\r\n",down1);
flag=1;
while(pwmin==0);
th2=TH2;
tl2=TL2;
// printf("高八位=%d\r\n",th2);
// printf("低八位=%d\r\n",tl2);
up=th2*256+tl2;
printf("up=%f\r\n",up);
break;
case 1:
// printf("高八位=%d\r\n",th2);
// printf("低八位=%d\r\n",tl2);
down2=tl2+th2*256;
P22=~P22;
printf("down2=%f\r\n",down2);
flag=0;
TR2=0;
ET2=0;
TH2=0;
TL2=0;
finish=1;
break;
default:break;
}
}
}