#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit DQ=P1^4; //ds18b20ä¸åçæºè¿æ¥å£
unsigned char code str[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x00,0x40} ; //å
±é´æ°ç 管åç 表
unsigned char code str1[]={0x0bf,0x86,0x0db,0x0cf,0x0e6,0x0ed,0x0fd,0x87,0x0ff,0x0ef}; //个ä½å¸¦å°æ°ç¹åç 表
unsigned char code wei[]={0x0fe,0x0fd,0x0fb,0x0f7};
uchar data disdata[5];
uint tvalue; //温度å¼
uchar tflag; //温度æ£è´æ å¿
/**********ds1820ç¨åº************/
void delay_18B20(unsigned int i) //延æ¶1å¾®ç§
{
while(i--);
}
void ds1820rst() /*ds1820å¤ä½*/
{
unsigned char x=0;
DQ = 1; //DQå¤ä½
delay_18B20(4); //延æ¶
DQ = 0; //DQæä½
delay_18B20(100); //精确延æ¶å¤§äº 480us
DQ = 1; //æé«
delay_18B20(40);
}
uchar ds1820rd() /*读æ°æ®*/
{
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_18B20(10);
}
return(dat);
}
void ds1820wr(uchar wdata) /*åæ°æ®*/
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ = 0;
DQ = wdata&0x01;
delay_18B20(10);
DQ = 1;
wdata>>=1;
}
}
read_temp() /*读å温度å¼å¹¶è½¬æ¢*/
{
uchar a,b;
ds1820rst();
ds1820wr(0xcc); // è·³è¿è¯»åºåå·
ds1820wr(0x44); // å¯å¨æ¸©åº¦è½¬æ¢
ds1820rst();
ds1820wr(0xcc); // è·³è¿è¯»åºåå·
ds1820wr(0xbe); // 读å温度
a=ds1820rd();
b=ds1820rd();
tvalue=b;
tvalue<<=8;
tvalue=tvalue|a;
if(tvalue<0x0fff)
tflag=0;
else
{
tvalue=~tvalue+2; tflag=1; //è´æ¸©åº¦
}
tvalue=tvalue*(0.625); //温度å¼æ©å¤§10åï¼ç²¾ç¡®å°1ä½å°æ°
return(tvalue);
}
/*********************************/
void ds1820disp() //温度å¼æ¾ç¤º
{
uchar i;
disdata[0]=tvalue/1000; //ç¾ä½æ°
disdata[1]=tvalue%1000/100; //åä½æ°
disdata[2]=tvalue%100/10; //个ä½æ°
disdata[3]=tvalue%10; //å°æ°ä½
if(tflag==0)
{
if(disdata[0]==0x00)
{
disdata[0]=0x0a; //ç¾ä½æ°ä½ä¸º0ä¸æ¾ç¤º
if(disdata[1]==0x00) disdata[1]=0x0a; //åä½æ°ä½ä¸º0ä¸æ¾ç¤º
}
}
else //è´æ¸©åº¦
{
disdata[0]=0x0b; //è´æ¸©åº¦ç¾ä½æ¾ç¤ºè´å·:-
if(disdata[1]==0x00) disdata[1]=0x0a; //åä½æ°ä½ä¸º0ä¸æ¾ç¤º
}
for(i=0;i<150;i++)
{
P2=wei[0];
P0=str[disdata[3]];
delay_18B20(20);
P2=wei[1];
P0=str1[disdata[2]];
delay_18B20(20);
P2=wei[2];
P0=str[disdata[1]];
delay_18B20(20);
P2=wei[3];
P0=str[disdata[0]];
delay_18B20(20);
}
}
/************主ç¨åº**********/
void main()
{
ds1820rst(); //åå§åæ¾ç¤º
while(1)
{
read_temp(); //读å温度
ds1820disp(); //æ¾ç¤º
}
}