DS18B20程序代码
/************************************************
标题:用温度传感器设计温度计
说明:第一位数码管0表示温度为正1表示为负,二三数码管表示温度值
*************************************************/
#include<at89x51.h>
#include<intrins.h>//要调用_nop_()函数
#define uchar unsigned char
#define uint unsigned int
uchar templ,temph,wm0,wmhh,wmh,wml;
uchar code table[]=
{ 0xC0,/*0*/
0xF9,/*1*/
0xA4,/*2*/
0xB0,/*3*/
0x99,/*4*/
0x92,/*5*/
0x82,/*6*/
0xF8,/*7*/
0x80,/*8*/
0x90,/*9*/
0x88,/*A*/
0x83,/*b*/
0xC6,/*C*/
0xA1,/*d*/
0x86,/*E*/
0x8E,/*F*/
};
sbit DQ=P3^7;
/**********************************/
void s_delay(uchar z) //1us段延时函数
{
while(z--);
}
void delay_ms(uint z) //1ms延时函数
{
uint x,y;
for(x=z;x>0;x--)
for(y=120;y>0;y--);
}
/****************************************
*************温度传感器模块**************
*****************************************/
//初始化
void init()
{
DQ=1;
_nop_();
DQ=0;
s_delay(90); //延时480us以上 实际延时
DQ=1;
s_delay(3); //延时15~60us 实际延时
while(DQ);
s_delay(30); //延时60~240us 实际延时
DQ=1;
}
//读数据
uchar read()
{
uchar n,b;
for(n=8;n>0;n--)
{
DQ=0;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
DQ=1;
_nop_();
if(DQ)
b=b|0x80;
if(n!=1)
b>>=1;
s_delay(12);
DQ=1;
}
return b;
DQ=1;
}
//写数据
void write(uchar date)
{
uchar i;
for(i=8;i>0;i--)
{
DQ=0;
_nop_();
if(date&0x01)
DQ=1;
else
DQ=0;
s_delay(12);
date>>=1;
DQ=1;
_nop_();
_nop_();
}
DQ=1;
}
//获取温度值
void readT()
{
init();
write(0xcc);
write(0x44);
delay_ms(100);//584ms
_nop_();
init();
write(0xcc);
write(0xbe);
_nop_();
templ=read();//两次read()的内容不同,read()里面一共可以读九次
temph=read();
_nop_();
wm0=(temph<<4)|(templ>>4);
wmhh=wm0/100;
wmh=(wm0%100)/10;
wml=(wm0%100)%10;
}
/**********************************************
*****************数码管显示模块****************
************************************************/
void display()
{
P0=table[wmhh];
P2=0x7f;
s_delay(10);
P2=0xff;
P0=table[wmh];
P2=0xbf;
s_delay(10);
P2=0xff;
P0=table[wml];
P2=0xdf;
s_delay(10);
P2=0xff;
}
/***************************************
****************主函数******************
****************************************/
void main()
{
uint s;
while(1)
{
readT();
s=5000;
while(s)
{
display();
s--;
}
}
}


