#include <at89c51RC2.h>
#include <intrins.h>
sbit DS18B20_IO = P3^7;
#define DS18B20_SKIP_ROM 0xCC
#define DS18B20_CONVERT_T 0x44
#define DS18B20_READ_SCRATCHPAD 0xBE
unsigned char DS18B20_Start(void) //初始化
{
unsigned int i;
unsigned char Ack;
DS18B20_IO=1;
DS18B20_IO=0;
i = 227;while (--i);//延时500us
DS18B20_IO=1;
i = 29;while (--i);//延时70us
Ack=DS18B20_IO;
i = 227;while (--i);//延时500us
return Ack;
}
void DS18B20_SendByte(unsigned char Byte)//写入一个字节
{
unsigned int j,i;
for(j=0; j<8; j++)
{
DS18B20_IO=0;
i = 4;while (--i);//延时10us
DS18B20_IO=Byte&(0x01<<j);
if(DS18B20_IO==1)
{
DS18B20_IO=1;
}
i = 23;while (--i);//延时50us
DS18B20_IO=1;
_nop_();_nop_();
}
}
unsigned char DS18B20_ReceiveByte(void)
{
unsigned char Byte=0x00;
unsigned int j,i;
for(j=0; j<8; j++)
{
DS18B20_IO=0;
i = 2;while (--i);//延时5us
DS18B20_IO=1;
i = 2;while (--i);//延时5us
if(DS18B20_IO==1)
{
Byte|=(0x01<<j);
}
i = 23;while (--i);//延时50us
DS18B20_IO=1;
_nop_();_nop_();
}
return Byte;
}
void ConvertT(void)
{
DS18B20_Start();
DS18B20_SendByte(DS18B20_SKIP_ROM);
DS18B20_SendByte(DS18B20_CONVERT_T);
}
float ReadT(void)
{
unsigned char LSB,MSB;
int Tmp;
float T;
DS18B20_Start();
DS18B20_SendByte(DS18B20_SKIP_ROM);
DS18B20_SendByte(DS18B20_READ_SCRATCHPAD);
LSB=DS18B20_ReceiveByte();
MSB=DS18B20_ReceiveByte();
Tmp=(MSB<<8)|LSB;
T=Tmp/16.0;
return T;
}

|