51單片機(jī)多路DS18B20溫度測(cè)量程序
/***************************************************************************************/
void delays(int us) //用于DS18B20的延時(shí)函數(shù)
{ int s;
for ( s=0; s
void rst(void)//DS18B20初始化
{
DQ = 1;
delays(2);
DQ = 0;
delays(30); //精確延時(shí) 480~960us
DQ = 1;
delays(8);
}
void write(unsigned char ku)//DS18B20寫函數(shù)
{
int i=0;
for (i=0;i<8;i++)
{
DQ=0;
DQ =ku&0x01;
delays(3);
DQ=1;
ku>>=1;
}
}
void match_rom(unsigned char *rom) //DS18B20匹配ROM函數(shù)
{
unsigned char i;
rst(); //初始化
write(0x55); //匹配ROM
for(i=8;i>0;i--)
{
write(*(rom+i-1));
}本文引用地址:http://m.butianyuan.cn/article/201611/323807.htm
}
unsigned int read(void) //DS18B20讀函數(shù),每次讀16位
{
int i=0;
unsigned int u=0;
for (i=0;i<16;i++)
{
DQ=0;
u>>=1;
DQ=1;
if(DQ) u|=0x8000;
delays(4);
}
return (u);
}
int read0(unsigned char *seria)//讀取對(duì)應(yīng)溫度值并轉(zhuǎn)換函數(shù)
{
int temperature ;
unsigned int tp;
unsigned int lsb;
rst(); //初始化
write(0xCC); //跳過(guò)RAM
write(0x44); //溫度轉(zhuǎn)換
rst(); //再次初始化
write(0xCC);
match_rom(seria); //匹配ROM函數(shù)調(diào)用
write(0xBE); //讀取存儲(chǔ)器指令
tp=read(); //讀取溫度值
if((tp&0xf800)==0xf800)//判斷正負(fù)數(shù)
{
fushu=1 ;
tp=~tp+1 ;
lsb=(unsigned int)(tp*6.25);
dian=lsb%100; //取小數(shù)部分
temperature=lsb/100;
}
else
{
fushu=0;
lsb=(unsigned int)(tp*6.25);
dian=lsb%100;
temperature=lsb/100;
}
return(temperature);
}
/*****************************************************************************************/
void main()
{
uint i ;
LCD_INIT();
EA=0 ; //使用DS18B20禁止任何中斷
while(1)
{
for(i=0;i<2;i++)
{
Tm=read0(get_serial+i*8);
if(i==0) //判斷是第幾個(gè)的數(shù)據(jù)
{
if(fushu==0) //判斷是否加負(fù)號(hào)
sprintf(LCD_LINE_ONE+5," %d", Tm);
if(fushu==1)
sprintf(LCD_LINE_ONE+5,"-%d", Tm);
sprintf(LCD_LINE_ONE+10,".%d",dian);//加入小數(shù)部分
Display_LCD_String(0x00,LCD_LINE_ONE);
}
if(i==1)
{
if(fushu==0)
sprintf(LCD_LINE_TWO+5," %d", Tm);
if(fushu==1)
sprintf(LCD_LINE_TWO+5,"-%d", Tm);
sprintf(LCD_LINE_TWO+10,".%d",dian);
Display_LCD_String(0x40,LCD_LINE_TWO);
}
}
}
}
評(píng)論