Files
STC89C51-Perpetual-Calendar/Keil Code/Last/ds18b20.c
T

109 lines
2.6 KiB
C

#include "ds18b20.h"
/*
* ????????DS18B20_Reset
* ???? ????¦ËDS18B20????????????
* ???? ????
* ??? ??1=?????0=??????
*/
bit DS18B20_Reset(void)
{
unsigned int i;
unsigned char presence;
DS18B20_DQ = 0; /* ????????480~960us */
for(i=250; i>0; i--); /* DJNZ???: 250*2=500us */
DS18B20_DQ = 1; /* ????????DS18B20????15~60us??????60~240us */
for(i=10; i>0; i--); /* DJNZ: 10*2=20us, ?????????? */
presence = DS18B20_DQ; /* ???????????(0=?????1=??????) */
for(i=200; i>0; i--); /* DJNZ: 200*2=400us, ????????? */
return (presence == 0); /* ????1?????????????? */
}
/*
* ????????DS18B20_WriteByte
* ???? ????DS18B20§Õ????????(LSB????)
* ???? ??dat=?§Õ???????
* ??? ????
*/
void DS18B20_WriteByte(uchar dat)
{
unsigned char i, j;
for(i=0; i<8; i++)
{
DS18B20_DQ = 0; /* ??????????§Õ?? */
if(dat & 0x01) /* §Õ1????????? */
DS18B20_DQ = 1;
else /* §Õ0?????????? */
DS18B20_DQ = 0;
for(j=35; j>0; j--); /* DJNZ: 35*2=70us, ?????>=60us */
DS18B20_DQ = 1; /* ??????? */
dat >>= 1; /* ???¦Ë(LSB first) */
}
}
/*
* ????????DS18B20_ReadByte
* ???? ????DS18B20?????????(LSB????)
* ???? ????
* ??? ????????????
*/
uchar DS18B20_ReadByte(void)
{
unsigned char i, j, dat = 0;
for(i=0; i<8; i++)
{
DS18B20_DQ = 0; /* ?????????????? */
DS18B20_DQ = 1; /* ??????? */
for(j=7; j>0; j--); /* DJNZ: 7*2=14us, ???DS18B20???????(~15us) */
dat >>= 1; /* ?????¦Ë */
if(DS18B20_DQ)
dat |= 0x80; /* LSB first?????????????¦Ë??????¦Ë */
for(j=23; j>0; j--); /* DJNZ: 23*2=46us, ?????>=60us */
}
return dat;
}
/*
* ????????DS18B20_StartConvert
* ???? ??????DS18B20??????
* ???? ????
* ??? ????
*/
void DS18B20_StartConvert(void)
{
if(!DS18B20_Reset()) return; /* ??¦Ë???????? */
DS18B20_WriteByte(0xCC); /* ????ROM */
DS18B20_WriteByte(0x44); /* ????????? */
}
/*
* ????????DS18B20_ReadTemp
* ???? ?????DS18B20??????(16¦Ë)
* ???? ??temp=??????????????
* ??? ??1=????????0=DS18B20¦Ä???
*/
bit DS18B20_ReadTemp(int *temp)
{
uchar tempL, tempH;
int raw;
if(!DS18B20_Reset()) return 0; /* ??¦Ë???????? */
DS18B20_WriteByte(0xCC); /* ????ROM */
DS18B20_WriteByte(0xBE); /* ??????? */
tempL = DS18B20_ReadByte(); /* ?????????? */
tempH = DS18B20_ReadByte(); /* ?????????? */
raw = (tempH << 8) | tempL; /* ???16¦Ë???? */
*temp = raw;
return 1;
}