#include
#include
#define BUSY1 (DQ1==0)
sbit DQ1 = P0^4;
unsigned char idata TMP;
unsigned char idata TMP_d;
unsigned char f;
void wr_ds18_1(char dat);
unsigned char rd_ds18_1();
/***************延时程序,单位us,大于10us*************/
void time_delay(unsigned char time)
{
time=time-10;
time=time/6;
while(time!=0)time--;
}
/*****************************************************/
/* reset ds18b20 */
/*****************************************************/
void ds_reset_1(void)
{
unsigned char idata count=0;
DQ1=0;
time_delay(240);
time_delay(240);
DQ1=1;
return;
}
void check_pre_1(void)
{
while(DQ1);
while(~DQ1);
time_delay(30);
}
void read_ROM(void)
{
int n;
ds_reset_1();
check_pre_1();
wr_ds18_1(0x33);
for(n=0;n<8;n++){ROM[n]=rd_ds18_1();}
}
/*****************************************************/
/* Read a bit from 1820 位读取 */
/*****************************************************/
bit tmrbit_1(void)
{
idata char i=0;
bit dat;
DQ1=0;_nop_();
DQ1=1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
dat = DQ1;
time_delay(50);
return dat;
}
/*****************************************************/
/* read a bety from ds18b20 字节读取 */
/*****************************************************/
unsigned char rd_ds18_1()
{
unsigned char idata i,j,dat=0;
for(i=1;i<=8;i++)
{
j=tmrbit_1();
dat=(j<<(i-1))|dat;
}
return dat;
}
/*****************************************************/
/* write a bety from ds18b20 写字节 */
/****************************************************/
void wr_ds18_1(char dat)
{
signed char idata i=0;
unsigned char idata j;
bit testb;
for(j=1;j<=8;j++)
{
testb=dat & 0x01;
dat = dat>>1;
if(testb)
{
DQ1=0;
_nop_();
_nop_();
DQ1=1;
time_delay(60);
}
else
{
DQ1=0;
time_delay(50);
DQ1=1;
_nop_();
_nop_();
}
}
}
int get_temp_1(void)
{
unsigned char idata a=0,b=0;
unsigned char idata i;
EA=0;
ds_reset_1();
check_pre_1();
wr_ds18_1(0xcc);
wr_ds18_1(0x44);
while(BUSY1);
ds_reset_1();
check_pre_1();
wr_ds18_1(0xcc);
wr_ds18_1(0xbe);
a=rd_ds18_1();
b=rd_ds18_1();
i=b; /*若b为1则为负温 */
i=(i>>4);
if(i==0)
{
f=0;
TMP=((a>>4)|(b<<4));
a=(a&0x0f);
if (a>8)
{
TMP=(TMP+1);
}
}
else
{
f=1;
a=a>>4;
b=b<<4;
TMP=(a|b);
TMP=~TMP;
TMP=(TMP+1);
}
EA=1;
return(TMP);
}
int get_temp_d(void)
{
unsigned char idata a=0,b=0;
unsigned char idata i,m;
EA=0;
ds_reset_1();//复位
check_pre_1();
wr_ds18_1(0xcc);
wr_ds18_1(0x44);
while(BUSY1);
ds_reset_1();
check_pre_1();
wr_ds18_1(0xcc);
wr_ds18_1(0xbe);
a=rd_ds18_1();
b=rd_ds18_1();
i=b; /*若b为1则为负温 */
i=(i>>4);
if(i==0)
{
f=0;
TMP=((a>>4)|(b<<4));
a=(a&0x0f);
TMP_d=a;
}
else
{
f=1;
a=~a;
a=(a+1);
b=~b;
b=(b+1);
m=a;
a=a>>4;
b=b<<4;
TMP=(a|b);
m=(m&0x0f);
TMP_d=m;
}
EA=1;
return(TMP);
}
评论
查看更多