|
#ifndef __DS18B20_H__
#define __DS18B20_H__
#define uchar unsigned char
#define uint unsigned int
sbit DQ = P1^5;
uchar tab[5];
uint temp;// 溫度值
bit tflag;
/****************
延時(shí)1 微秒**********/
void delay_18B20(uint i)
{
while(i--);
}
/*******************
ds1820 復(fù)位************/
void ds1820rst()
{
uchar x=0;
DQ=1; //DQ 復(fù)位
delay_18B20(8); // 延時(shí)
DQ=0; //DQ 拉低
delay_18B20(80); // 精確延時(shí)大于480us
DQ=1; // 拉高
delay_18B20(14);
x=DQ; // 稍做延時(shí)后如果
//x=0則初始化成功 x=1 則初始化失敗
while(!DQ);
delay_18B20(20);
}
/********************
讀一個(gè)字節(jié)********************/
uchar ds1820rd()
{
uchar i=0;
uchar dat=0;
for (i=8;i>0;i--)
{
DQ=0; // 給脈沖信號(hào)
dat>>=1;
DQ=1; // 給脈沖信號(hào)
if(DQ)
dat|=0x80;
delay_18B20(4);
}
return(dat);
}
/***************
寫一個(gè)字節(jié)***************/
void ds1820wr(uchar dat)
{
uchar i=0;
for (i=8;i>0;i--)
{
DQ=0;
DQ=dat&0x01;
delay_18B20(5);
DQ=1;
dat>>=1;
}
}
/**************** 讀取溫度
值并轉(zhuǎn)換***************/
read_temp()
{
uchar a,b;
ds1820rst();
ds1820wr(0xcc);// 跳過讀序列號(hào)
ds1820wr(0x44);// 啟動(dòng)溫度轉(zhuǎn)換
delay_18B20(100);
ds1820rst();
ds1820wr(0xcc);// 跳過讀序列號(hào)
ds1820wr(0xbe);// 讀取溫度
delay_18B20(100);
a=ds1820rd();
b=ds1820rd();
temp=b;
temp<<=8;
temp=temp|a;
if(temp<0x0fff)
tflag=0;
else
{
temp=~temp+1;
tflag=1;
}
temp=temp*(0.625);// 溫度值擴(kuò)大10倍,
//精確到1 位小數(shù)
return(temp);
}
/*****************
溫度值顯示****************/
void ds1820disp()
{
uchar flagdat;
read_temp();
tab[0]=temp%1000/100+0x30; //
//十位數(shù)
tab[1]=temp%100/10+0x30; //
//個(gè)位數(shù)
tab[2]=temp%10+0x30; //
//小數(shù)位
if(tflag==0)
flagdat=0x20;// 正溫度不顯示符號(hào)
else
flagdat=0x2d;// 負(fù)溫度顯示負(fù)號(hào):-
if(tab[0]==0x30) { tab[0]=0x20; }// 如果十位為0,不顯示
write_com(0x80+0x40+6);
write_dat(flagdat); // 顯示正負(fù)
write_dat(tab[0]); // 顯示十位
write_dat(tab[1]); // 顯示個(gè)位
write_dat(0x2e); // 顯示小數(shù)
//點(diǎn)
write_dat(tab[2]); // 顯示小數(shù)位
write_dat(0xdf);
write_dat(0x43);
}
#endif
|
|