新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設計應用 > [C51代碼]DS18B20驅動

[C51代碼]DS18B20驅動

作者: 時間:2016-11-10 來源:網絡 收藏

/*******************ds18b20.c**************************/
#include "Atmel/AT89X51.h"
#include "link.h"
#include "ds18b20.h"
#include "delay.h"

本文引用地址:http://butianyuan.cn/article/201611/317078.htm

/**************定量定義***************/
union
{
uchar c[2];
uint x;

}temp;

uchar idata flag=0;
uint idata cc=0;
uchar idata disp[8];

/****************************************************************
*函數功能:復位DS18B20
*入口參數:無
*出口參數:presence,指示復位是否成功
****************************************************************/
uchar Reset_DS18B20(void)
{
uchar presence;
DQ = 0; //pull DQ line low
delay(248); // leave it low for 500us
DQ = 1; // allow line to return high
delay(48); // wait for presence 100us
presence = DQ; // get presence signal
delay(198); // wait for end of timeslot 400us
return(presence); // presence signal returned
} // 0=presence, 1 = no part

/****************************************************************
*函數功能:讀取DS18B20的一個字節(jié)
*入口參數:無
*出口參數:value,讀取的一個字節(jié)
****************************************************************/
uchar read_byte(void)
{
uchar i;
uchar value = 0;
for (i=8;i>0;i--)
{
value>>=1;
DQ = 0; // pull DQ low to start timeslot
DQ = 1; // then return high
delay(3); // 11us
if(DQ) value|=0x80;
delay(25); // wait for rest of timeslot 55us
}
return(value);
}

/****************************************************************
*函數功能:寫一個字節(jié)到DS18B20
*入口參數:val,要寫的一個字節(jié)
*出口參數:無
****************************************************************/
void write_byte(uchar val)
{
uchar i;
for (i=8; i>0; i--)
{
DQ = 0; // pull DQ low to start timeslot
DQ = val&0x01; // 寫1時,使得15us以內拉高 整個寫1時隙不低于60us,寫0時保持低在60us到120us之間
delay(38); // hold value for remainder of timeslot 80us
DQ = 1;
val=val/2;
}
delay(38); //80us
}
/****************************************************************
*函數功能:讀取DS18B20的溫度值
*入口參數:無
*出口參數:temp.x溫度值
****************************************************************/
uint Read_Temperature(void)
{ EA=0;
Reset_DS18B20();
write_byte(0xCC); // Skip ROM
write_byte(0xBE); // Read Scratch Pad
temp.c[1]=read_byte();
temp.c[0]=read_byte();
Reset_DS18B20();
write_byte(0xCC); //Skip ROM
write_byte(0x44); // Start Conversion
return temp.x;
}
/****************************************************************
*函數功能:將DS18B20的溫度值送LCD顯示
*入口參數:無
*出口參數:無
****************************************************************/
void DS18B20Disp(void)
{
flag=0; //溫度正負標志位
cc=Read_Temperature();
if (cc>0xf800)
{
flag=1;

cc=~cc+1;
}
cc=cc*0.625;

disp[0]=0+cc/1000;
disp[1]=0+(cc/100)%10;
disp[2]=0+(cc/10)%10;
disp[3]=.; //小數點
disp[4]=0+cc%10;
disp[5]=0xdf;
disp[6]=C;
disp[7]=