/////////////////////////////////////////////
//名 稱 :DS18B20溫度的讀取
//開發者:zhangchunhua
//環 境 :PIC單片機
//時 序 :4.00 晶振
/////////////////////////////////////////////
#include<pic.h>
/////////////////////////////////////////////
#define uchar unsigned char
#define uint unsigned int
/////////////////////////////////////////////
#define DQ RC3
#define DQ_HIGH() TRISC3=1
#define DQ_LOW() TRISC3=0;DQ=0
/////////////////////////////////////////////
void reset(void);
void write_byte(uchar date);
uchar read_byte(void);
void yanshius(uint t);
void start_t(void);
signed int read_t(void);
/////////////////////////////////////////////
void yanshius(uint t)
{
uint i;
for(i=0;i<t;i++)
{ NOP(); }
}
void reset(void)
{
uchar st=1;
while(st)
{
DQ_LOW();
yanshius(29);//510uS
DQ_HIGH();
yanshius(2);//60uS
if(DQ==1)
st=1;
else
{ st=0;
yanshius(25);//480uS
}
}
}
void write_byte(uchar date)
{
uchar i,temp;
for(i=8;i>0;i--)
{
temp=date & 0x01;//01010101
DQ_LOW();
if(temp == 1)
{ NOP();NOP();
DQ_HIGH();
yanshius(2);
}
else
{
yanshius(2);//60uS
DQ_HIGH();
}
NOP();NOP();
date = date>>1;//00101010yanshius(0);
}
}
uchar read_byte(void)
{
uchar i,date;
static bit j;
for(i=8;i>0;i--)
{
date = date>>1;
DQ_LOW();
NOP();NOP();
DQ_HIGH();
NOP();NOP();NOP();NOP();NOP();NOP();NOP();
j = DQ;
if(j == 1)
{
date=date|0x80;//1000 0000
}
yanshius(1);//47uS
}
return date;
}
void start_t(void)
{
reset(); //復位
write_byte(0xCC);//跳過ROM
write_byte(0x44);//溫度轉換
}
//////讀取的溫度數值是放大10倍
signed int read_t(void)
{
uchar tem1,tem2;
uint tt,mm=0;
double aaa;
signed int temper;
reset();
write_byte(0xCC);
write_byte(0xBE);
tem1=read_byte();
tem2=read_byte();
tt = tem2;
tt = tt<<8|tem1;
if(tt&0x8000)
{
mm = ~tt + 1;
aaa = mm * (-0.625);
}
else
{
aaa = tt*0.625;
}
temper=(signed int)aaa;
return temper;
}
|