DS18B20能读数据但数据错误
时间:10-02
整理:3721RD
点击:
程序分享出来给需要的人作参考
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit DQ=P2^2; //DS18B20单总线
sbit dula=P2^6; //控制数码管段选的锁存器
sbit wela=P2^7; //控制数码管位选的锁存器
sbit rs=P3^5;
sbit lcden=P3^4;
sbit s1=P3^0;
sbit s2=P3^1;
sbit s3=P3^2;
sbit rd=P3^7;
sbit wr=P3^6;
void delay(int us)
{
int s;
for(s=0;s<us;s++);
}
void delay1(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void write_com(uchar com)
{
rs=0;
lcden=0;
P0=com;
delay1(5);
lcden=1;
delay1(5);
lcden=0;
}
void write_date(uchar date)
{
rs=1;
lcden=0;
P0=date;
delay1(5);
lcden=1;
delay1(5);
lcden=0;
}
void init()
{
wr=0;
dula=0;
wela=0;
lcden=0;
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
write_com(0x80);
}
uchar reset()
{
uchar presence;
DQ=0;
delay(29);
DQ=1;
delay(3);
presence=DQ;
delay(25);
return(presence);
}
uchar read_bit()
{
uchar i;
DQ=0;
DQ=1;
for(i=0;i<3;i++);
return(DQ);
}
void write_bit(char bitval)
{
DQ=0;
if(bitval==1)DQ=1;
delay(5);
DQ=1;
}
uchar read_byte()
{
uchar i;
uchar value=0;
for(i=0;i<8;i++)
{
if(read_bit())value|=0x01<<i;
delay(6);
}
return(value);
}
void write_byte(char val)
{
uchar i;
uchar temp;
for(i=0;i<8;i++)
{
temp=val>>i;
temp&=0x01;
write_bit(temp);
}
delay(5);
}
uint get_tmp()
{
uchar a,b,temp;
float tt;
reset();
write_byte(0xcc);//SkipROM
write_byte(0x44);//开始转换
delay(31);
reset();
write_byte(0xcc);
write_byte(0xbe);
a=read_byte();
b=read_byte();
temp=b;
temp<<=8; //two byte compose a int variable
temp=temp|a;
tt=temp*0.0625;
temp=tt*10+0.5;
return(temp);
}
void display(uchar num)
{
uchar bai,shi,ge;
bai=num/100;
shi=(num%100)/10;
ge=(num%100)%10;
write_com(0x80);
write_date(0x30+bai);
write_com(0x81);
write_date(0x30+shi);
write_com(0x82);
write_date(0x30+ge);
}
void main()
{
uchar a;
uint tmp;
init();
while(1)
{
for(a=28;a>0;a--)
{
tmp=get_tmp();
display(tmp);
delay(60);
}
}
}
哎。没人回呀~
高手帮帮忙。
把转换时间调长一点
问题解决了,谢谢朋友了。
转换时间是在那一段程序中,高手能解释一下吗
get_tmp()函数中的delay函数就是转换时间