可不是一个错误...
现在就剩下一个错误了,你自己纠正吧...
#include <reg51.h>
#include<intrins.h> //nop函数
#include<math.h>
#include<stdlib.h>
#define uchar unsigned char
#define uint unsigned int
sbit DS18B20_DQ=P2^3; //温度传感器连接在P2.3引脚
uchar DS18B20_serial[3][8]={0x28,0x51,0x8c,0x9e,0x03,0x00,0x00,0xfd, //第1个18B20的ID
0x28,0x71,0x91,0x9e,0x03,0x00,0x00,0xdb, //第2个18B20的ID
0x28,0x43,0xa6,0x9a,0x03,0x00,0x00,0x83, //第3个18B20的ID
};
sbit LED1=P1^1;
sbit LED2=P1^2;
sbit LED3=P1^3;
void delay(uint time) //延时函数
{
uint i;
while(time)
{ i=200;
while(i>0)
i--;
time--;
}
}
void dereset(void)//DS18B20初始化子程序
{ uint i;
DS18B20_DQ=1; //复位脉冲
_nop_();
_nop_();
DS18B20_DQ=0;
i=103;
while(i>0)
i--;
DS18B20_DQ=1;
i=4;
while(i>0)
i--;
}
bit readbit(void) //从DS18B20读一位
{ uint i;
bit dat;
DS18B20_DQ=0;//;
i++;//延时
DS18B20_DQ=1;
i++;
i++;
dat=DS18B20_DQ;
i=8;
while(i>0)
i--;
return(dat);
}
uchar read_DS18B20(void) // 从resd_DS18B2读一个字节
{
uchar i,j,dat;
dat=0;
for(i=1;i<=8;i++)
{
j=readbit();
dat=(j<<7)|(dat>>1); //将数据的最低位放在前面
}
return(dat);//返回字节数据
}
void writebyte(uchar dat)//写一个字节
{
uint i;//;
uchar j;
bit testb;
for(j=1;j<<8;j++)
{
testb=dat&0x01;
dat=dat>>1;
if (testb)
{
DS18B20_DQ=0;
i++;
i++;
DS18B20_DQ=1;
i=8;
while(i>0)
i--;
}
else
{
DS18B20_DQ=0;
i=8;
while(i>0)
i--;
DS18B20_DQ=1;
i++;i++;
}
}
}
uint gettemp(uchar num) //读取温度值
{
uchar i;
uchar templ=0;
uint temph=0;
dereset();//初始化DS18B20
delay(1);//延时
writebyte(0x55);//匹配ROM指令
writebyte(0xcc);//跳过ROM
for (i=0;i<8;i++)
writebyte(DS18B20_serial[num][i]);//发出64位ROM码
writebyte(0x44);//启动温度转换
delay(1);//延时
dereset();
writebyte(0x55);
for (i=0;i<8;i++)
writebyte(DS18B20_serial[num][i]);
writebyte(0xbe);//读取温度
templ= read_DS18B20();
temph= read_DS18B20();
temph<<=8;
temp=(uint)(temph|templ)*0.0625;
return(temp);
}
void main()
{ uint i;
uchar temper;
while(1)
{
i=1;
temper=gettemp(i);
if(temper<15)
LED1=1;
elseif(temper>18)
LED1=0;
end
i++;
temper=gettemp(i);
if(temper<22)
LED2=1;
elseif(temper>25)
LED2=0;
end
i++;
temper=gettemp(i);
if(temper<30)
LED3=1;
elseif(temper>35)
LED3=0;
end
delay(1000);
}
} |