求一个ds18b20数字温度测量的C程序

2024-12-15 00:57:20
推荐回答(1个)
回答1:

#include"reg51.h"
#include"intrins.h"

unsigned char templ=0;
unsigned char temph=0;
unsigned char tempdot=0;
bit fuhao_flag=0;
float temperature=0;
unsigned char t=0;

unsigned char tab[11]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xbf};
unsigned char ledbitpos=0;

sbit dq=P1^0;

sbit num_shiwei=P2^5;
sbit num_gewei=P2^4;
sbit fuhaowei=P2^3;
sbit shiwei=P2^2;
sbit gewei=P2^1;
sbit dot=P2^0;

void Delay5us(unsigned char n)
{
unsigned char i;
i=n;
do
{
_nop_();_nop_();_nop_();
i--;
}
while(i);
return;
}

void Delay5ms(unsigned char n)
{
unsigned char i;
i=n;
do
{

Delay5us(200);
Delay5us(200);
Delay5us(200);
Delay5us(200);
Delay5us(200);
i--;
}
while(i);

}

bit init_ds18b20(void)
{
bit bresult=0;
EA=0;
dq=1;
Delay5us(8);

dq=0;
Delay5us(90);
dq=1;
Delay5us(6);

bresult=dq;
Delay5us(20);

EA=1;
return bresult;
}

bit readbit()
{
bit b;

dq=0;

_nop_();
_nop_();
_nop_();
_nop_();

dq=1;

_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();

b=dq;

Delay5us(4);

return b;
}

unsigned char readonechar(void)
{
unsigned char i=0;
unsigned char dat=0;
EA=0;

for(i=8;i>0;i--)
{
dat=_cror_(dat,1);
if(readbit())
dat|=0x80;

else
dat|=0x00;
}
EA=1;
return dat;
}

void writebit(bit dq1)
{
unsigned char j;
if(!dq1)
{
dq=0;
for(j=35;j>0;j--);
dq=1;
}
else
{
dq=0;
for(j=2;j>0;j--);
dq=1;
for(j=33;j>0;j--);

}
}

void writeonechar(unsigned char command)
{
unsigned char i;
EA=0;

for(i=0;i<8;i++)
{
writebit(command & 0x01);

command=_cror_(command,1);

}
EA=1;
}

void t0() interrupt 1 using 0
{
TH0=0xf8;
TL0=0x30;
ledbitpos++;

switch(ledbitpos)
{
case 1:
P0=tab[tempdot];
fuhaowei=0;
shiwei=0;
gewei=0;
dot=1;
break;

case 2:
P0=0x7f & tab[t%10];
fuhaowei=0;
shiwei=0;
gewei=1;
dot=0;
break;

case 3:
P0=tab[t%100/10];
fuhaowei=0;
shiwei=1;
gewei=0;
dot=0;
break;

case 4:
if(fuhao_flag==0)
{
P0=tab[t/100];
fuhaowei=1;
shiwei=0;
gewei=0;
dot=0;
}
else
{
P0=tab[10];
fuhaowei=1;
shiwei=0;
gewei=0;
dot=0;
}
break;

default:
ledbitpos=0;
break;
}

}

void display232(unsigned i)
{
TI=0;
SBUF=i/100+48;
while(TI==0);

TI=0;
SBUF=i%100/10+48;
while(TI==0);

TI=0;
SBUF=i%10+48;
while(TI==0);

TI=0;
SBUF=46;
while(TI==0);

TI=0;
SBUF=tempdot+48;
while(TI==0);

TI=0;
SBUF=0x0d;
while(TI==0);

TI=0;
SBUF=0x0a;
while(TI==0);

}

void main(void)
{

TMOD=0x21;
TH0=0xf8;
TL0=0x30;
ET0=1;
EA=1;
TR0=0;

TH1=0xfd;
TL1=0xfd;
SCON=0xd8;PCON=0x00;
TR1=1;
while(1)

{
if(!init_ds18b20())
{
writeonechar(0xcc);
writeonechar(0x44);
Delay5ms(200);
}

if(!init_ds18b20())

{
writeonechar(0xcc);
writeonechar(0xbe);
templ=readonechar();
temph=readonechar();

}
fuhao_flag=temph>>4;
tempdot=(10*(templ & 0x0f))/16;
templ=templ>>4;
t=temph<<4;
t=t|templ;

display232(t);
TR0=1;
}

}
这是我们实训用的程序,虽然和你的图不一样,但18b20的初始化,相关思想一样,望对你有所帮助