/*--------------------------------------------------------------------------------------------------- 功能:實(shí)現(xiàn)對DS18B20的讀取 原理:單總線協(xié)議 注意:單總線協(xié)議對延時要求比較嚴(yán)格,此程序中采用的是11.0592M的晶振,如果使用其他的晶振請跟據(jù)DS18B20的資料修改延時參數(shù) 版本:1.4b 最后修改時間:2004年11月8號 開發(fā)人:鞠春陽 版權(quán):哈爾濱眾邦龍開發(fā)有限公司 http://www.hitzbl.com/ 單片機(jī)坐標(biāo)網(wǎng):www.mcuzb.com ====================================================================================================*/ //#include"reg51.h" sbit DQ =P1^4; //定義通信端口 //延時函數(shù) /* void delay(unsigned int i) { while(i--); } */ //初始化函數(shù) Init_DS18B20(void) { unsigned char x=0; DQ = 1; //DQ復(fù)位 delay(8); //稍做延時 DQ = 0; //單片機(jī)將DQ拉低 delay(80); //精確延時 大于 480us DQ = 1; //拉高總線 delay(14); x=DQ; //稍做延時后 如果x=0則初始化成功 x=1則初始化失敗 delay(20); } //讀一個字節(jié) ReadOneChar(void) { unsigned char i=0; unsigned char dat = 0; for (i=8;i>0;i--) { DQ = 0; // 給脈沖信號 dat>>=1; DQ = 1; // 給脈沖信號 if(DQ) dat|=0x80; delay(4); } return(dat); } //寫一個字節(jié) WriteOneChar(unsigned char dat) { unsigned char i=0; for (i=8; i>0; i--) { DQ = 0; DQ = dat&0x01; delay(5); DQ = 1; dat>>=1; } //delay(4); } //讀取溫度 ReadTemperature(void) { unsigned char a=0; unsigned char b=0; unsigned int t=0; float tt=0; Init_DS18B20(); WriteOneChar(0xCC); // 跳過讀序號列號的操作 WriteOneChar(0x44); // 啟動溫度轉(zhuǎn)換 Init_DS18B20(); WriteOneChar(0xCC); //跳過讀序號列號的操作 WriteOneChar(0xBE); //讀取溫度寄存器等(共可讀9個寄存器) 前兩個就是溫度 a=ReadOneChar(); b=ReadOneChar(); t=b; t<<=8; t=t|a; tt=t*0.0625; //t= tt*10+0.5; //放大10倍輸出并四舍五入---此行沒用 return(t); }
main() { unsigned char i=0; while(1) { i=ReadTemperature();//讀溫度 } }
|