#include <reg52.h>
#include <ds18b20.h>
#include <intrins.h>
unsigned
char
temp_i=0;
void
DelayX10us(unsigned
char
t)
{
do
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
while
(--t);
}
unsigned
char
Get18B20Ack()
{
unsigned
char
ack;
EA = 0;
IO_18B20 = 0;
DelayX10us(50);
IO_18B20 = 1;
DelayX10us(6);
ack = IO_18B20;
while
(!IO_18B20);
EA = 1;
return
ack;
}
void
Write18B20(unsigned
char
dat)
{
unsigned
char
mask;
EA = 0;
for
(mask=0x01; mask!=0; mask<<=1)
{
IO_18B20 = 0;
_nop_();
_nop_();
if
((mask&dat) == 0)
IO_18B20 = 0;
else
IO_18B20 = 1;
DelayX10us(6);
IO_18B20 = 1;
}
EA = 1;
unsigned
char
Read18B20()
{
unsigned
char
dat;
unsigned
char
mask;
EA = 0;
for
(mask=0x01; mask!=0; mask<<=1)
{
IO_18B20 = 0;
_nop_();
_nop_();
IO_18B20 = 1;
_nop_();
_nop_();
if
(!IO_18B20)
dat &= ~mask;
else
dat |= mask;
DelayX10us(6);
}
EA = 1;
return
dat;
}
unsigned
char
Start18B20()
{
unsigned
char
ack;
ack = Get18B20Ack();
if
(ack == 0)
{
Write18B20(0xCC)
Write18B20(0x44);
}
return
!ack;
}
unsigned
char
Get18B20Temp(
int
*temp)
{
unsigned
char
ack;
unsigned
char
LSB, MSB;
ack = Get18B20Ack();
if
(ack == 0)
{
Write18B20(0xCC);
Write18B20(0xBE);
LSB = Read18B20();
MSB = Read18B20();
*temp = ((unsigned
int
)MSB << 8) + LSB;
}
return
!ack;
}
unsigned
char
TEMP_CONV(unsigned
int
*temp, unsigned
char
*str)
{
unsigned
char
res;
float
temp_float;
res = Get18B20Temp(temp);
if
(res)
{
if
( (*temp>>11)==0 )
{
temp_float=( (
float
)(*temp) ) *0.0625*10.0;
*temp=(unsigned
int
)temp_float;
str[0]=
'0'
+( (*temp/1000)%10 );
str[1]=
'0'
+( (*temp/100)%10 );
str[2]=
'0'
+( (*temp/10)%10 );
str[3]=
'.'
;
str[4]=
'0'
+( (*temp)%10 );
if
(str[0]==
'0'
)temp_i++;
if
(str[1]==
'0'
)temp_i++;
return
1;
}
else
if
( (*temp>>11)>0 )
{
*temp=(*temp)&0x07FF;
*temp=2048-(*temp);
temp_float=( (
float
)(*temp) )*0.0625*10.0;
*temp=(unsigned
int
)temp_float;
str[0]=
'-'
;
str[1]=
'0'
+( (*temp/100)%10 );
str[2]=
'0'
+( (*temp/10)%10 );
str[3]=
'.'
;
str[4]=
'0'
+( (*temp)%10 );
if
(str[1]==
'0'
)
{
str[1]=
'-'
;
temp_i=1;
}
return
1;
}
}
return
0;
}