新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計應(yīng)用 > 簡單的DS18B20溫度測試

簡單的DS18B20溫度測試

作者: 時間:2016-11-25 來源:網(wǎng)絡(luò) 收藏
DS18B20是目前比較常用的一種溫度測試芯片。其具有微型化、低功耗、高性能、抗干擾強等優(yōu)點。同時可以直接將溫度轉(zhuǎn)化為數(shù)字信號提供給處理器。詳細的資料請參見芯片的資料說明。

本實驗是一個簡單的溫度檢測實驗。單片機將檢測到的溫度用數(shù)碼管顯示。程序如下:

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

=================================================================================================

#include
#define uchar unsigned char
#define uint unsigned int
int a,b,c,temp;
sbit DS=P3^3;//18B20端口設(shè)置
uchar code table[]={
0x3F, //"0"
0x06, //"1"
0x5B, //"2"
0x4F, //"3"
0x66, //"4"
0x6D, //"5"
0x7D, //"6"
0x07, //"7"
0x7F, //"8"
0x6F //"9"
};

void dsdelay(int num)// 延時10約為53us 時鐘為11.0592M
{
while(num--);
}

void delay(uint z) //延時函數(shù)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}

int init() //18B20初始化
{
uchar x=0;
DS=1;
dsdelay(8);//延時44us
DS=0;
dsdelay(110); //延時約500us
DS=1;
dsdelay(14); //稍微延時,讀取x
x=DS;
dsdelay(20);
}

uchar readchar() //從18B20中讀取1個字節(jié)
{
uchar i=0;
uchar dat;
for(i=8;i>0;i--)
{
DS=0;
dat>>=1;
DS=1;
if(DS)
dat|=0x80;
dsdelay(4);
}
return(dat);
}

void writechar(uchar dat) //向18B20中寫數(shù)據(jù)
{
uchar i=0;
for(i=8;i>0;i--)
{
DS=0;
DS=dat&0x1;
dsdelay(5);
DS=1;
dat>>=1;
}
}

uint readtemp() //讀取溫度值
{
uchar a;
uchar b;
uint t;
float tt;
a=0;
b=0;
t=0;
tt=0;
init();

writechar(0xcc); //跳過讀序號列號的操作
writechar(0x44); // 啟動溫度轉(zhuǎn)換
init();
writechar(0xcc); //跳過讀序號列號的操作
writechar(0xbe); //讀取溫度寄存器
a=readchar(); //讀高8位
b=readchar(); //讀高8位
t=b;
t<<=8;
t=t|a;//兩字節(jié)合成一個整型變量。
tt=t*0.0625; //得到真實十進制溫度值,因為DS18B20可以精確到0.0625度,所以讀回數(shù)據(jù)的最低位代表的是0.0625度
t= tt*10+0.5; //放大十倍,這樣做的目的將小數(shù)點后第一位也轉(zhuǎn)換為可顯示數(shù)字,同時進行一個四舍五入操作。
return(t);
}

void display() //數(shù)碼管顯示溫度值
{
P1=0xf0; //位選
P2=table[a];//段選
delay(3);
P1=0xf1;
P2=table[b];
delay(3);
P1=0xf2;
P2=0x08;
delay(3);
P1=0xf3;
P2=table[c];
}
void main()//主函數(shù)
{
int m;
m=0;
while(1)
{
if(m==0) //消除85現(xiàn)象
{
delay(500);
temp=readtemp();
delay(500);
delay(200);
m=1;
}
else
{
temp=readtemp();
a=temp/100;
b=temp0/10;
c=temp;
display();
}
}

}



關(guān)鍵詞: DS18B20溫度測

評論


技術(shù)專區(qū)

關(guān)閉