#include <Reg52.h>
//18B20的ID,调用DQ_ReadID函数获得您的18B20的ID
unsigned char code DQ_ID[2][8]={
                                0x28,0xa3,0x38,0x40,0x01,0x00,0x00,0xea,    //第1个18B20的ID
                                0x28,0x31,0x05,0x40,0x01,0x00,0x00,0x5d     //第2个18B20的ID
                               };
sbit DQ=P3^7;
//---------------------------------------------------------------------------------
void DQ_Delay(unsigned int t)
{
 for (;t>0;t--);
}
//---------------------------------------------------------------------------------
bit DQ_Reset(void)
{
 bit b;
 DQ =0;             //pull DQ line low
 DQ_Delay(480);     //leave it low for 480us
 DQ =1;             //allow line to return high
 DQ_Delay(5);       //wait for presence
 b =DQ;             //get presence signal
 DQ_Delay(25);      //wait for end of timeslot
 return b;          //presence signal returned
}                   //0=presence,1 =no part
//---------------------------------------------------------------------------------
void DQ_SendByte(unsigned char cData)
{
 unsigned char n;
 bit b;
 for (n=0;n<8;n++)      //writes byte,one bit at a time
    {
     b =(cData>>n)&1;   //shifts cData right 'n'spaces
     DQ =0;             //pull DQ low to start timeslot
     if(b) DQ =1;       //return DQ high if write 1
     DQ_Delay(5);       //hold cData for remainder of timeslot
     DQ =1;
    }
 DQ_Delay(5);
}
//---------------------------------------------------------------------------------
unsigned char DQ_RecByte()
{
 unsigned char n;
 unsigned char cData =0;
 for (n=0;n<8;n++)
    {
     DQ =0;     //pull DQ low to start timeslot
     DQ =1;     //then return high
     DQ_Delay(0);           //DQ_Delay 15us from start of timeslot 
     if(DQ) cData|=(0x01<<n);   //reads byte in,one byte at a time and then shifts it left
     DQ_Delay(2);           //wait for rest of timeslot
    }
 return(cData);
}
//---------------------------------------------------------------------------------
//获取温度值,cIdx是18B20编号:cIdx=1、2...等
unsigned int DQ_ReadTemp(unsigned char cIdx)
{
 unsigned char n;
 unsigned int i;
 
 DQ_SendByte(0xcc); //Skip ROM
 DQ_SendByte(0x44); // Start Conversion
 while(!DQ);        //等待转换结束
 DQ_Reset();
 //DQ_SendByte(0xcc); // Skip ROM
 DQ_SendByte(0x55); //发送ID匹配命令
 for(n=0;n<8;n++)  DQ_SendByte(DQ_ID[cIdx][n]); //发送64 bit ID
 DQ_SendByte(0xbe); // Read Scratch Pad
 i=DQ_RecByte(); //读取2Byte温度值
 i=i|(DQ_RecByte()<<8);
 if(i&0x8000) 
    {
     i=~i+1; //如果是零下,则去除补码
     i|=0x8000; //仍旧标记最高为1,表示零下返回。
    }
 return i*0.625;
}
//---------------------------------------------------------------------------------
void DQ_ReadID(unsigned char *p)
{
 unsigned char n;
 DQ_Reset();
 DQ_SendByte(0x33); //Skip ROM 
 for(n=0;n<8;n++) *p++=DQ_RecByte(); //读取64位ROM ID
}