#include<reg51.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit w1=P2^4;
sbit w2=P2^5;
sbit w3=P2^6;
sbit w4=P2^7;
sbit DQ=P3^7;
uint temp;
float f_temp; //溫度值 variable of temperature
bit flag;
uchar code table[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f
,0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,0x87,0xff,0xef };
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void Init_Ds18b20(void) //DS18B20初始化send reset and initialization command
{
uint i;
DQ = 0; //單片機拉低總線
i=70; while(i>0)i--;
DQ = 1; //釋放總線,即拉高了總線 i=4; while(i>0)i--; }
bit Read_One_bit() //讀取一個字節(jié)的數(shù)據(jù)read a byte date
//讀數(shù)據(jù)時,數(shù)據(jù)以字節(jié)的最低有效位先從總線移出
{
uint i;
bit dat;
DQ=0;i++;
DQ=1;i++;i++;
dat=DQ;
i=3;while(i>0)i--;
return (dat);
}
uchar Read_One_Byte(void)
{
uchar i,j,dat;
dat=0;
for(i=1;i<=8;i++)
{
j=Read_One_bit();
dat=(j<<7)|(dat>>1);
}
return (dat);
}
void Write_One_Byte(uchar dat)
{
uint i;
uchar j;
bit testb;
for(j=1;j<=8;j++)
{
testb=dat&0x01;
dat=dat>>1;
if(testb)
{
DQ=0;i++;i++;
DQ=1;
i=5;while(i>0)i--;
}
else
{
DQ=0;
i=5;while(i>0)i--;
DQ=1;
i++;i++;
}
}
}
void tmpchange(void)
{
uchar f;
Init_Ds18b20();
f=70;while(f>0)f--;
delay(1);
Write_One_Byte(0xcc); //忽略ROM指令
Write_One_Byte(0x44); //溫度轉(zhuǎn)換指令
}
uint Get_Tmp() //獲取溫度get the temperature
{
uchar a,b,f;
Init_Ds18b20(); //初始化
f=70;while(f>0)f--;
Write_One_Byte(0xcc); //忽略ROM指令
Write_One_Byte(0xbe); //溫度轉(zhuǎn)換指令
a = Read_One_Byte(); //讀取到的第一個字節(jié)為溫度LSB
b = Read_One_Byte(); //讀取到的第一個字節(jié)為溫度MSB
temp = b; //先把高八位有效數(shù)據(jù)賦于temp
temp <<= 8; //把以上8位數(shù)據(jù)從temp低八位移到高八位
temp = temp|a; //兩字節(jié)合成一個整型變量
f_temp = temp*0.0625;
temp = f_temp*10+0.5; //放大十倍
f_temp=f_temp+0.5; //同時進(jìn)行一個四舍五入操作。
return temp;
}
/****************數(shù)碼碼動態(tài)顯示函數(shù)**************/
void Display(uint temp) //顯示程序
{
uint A1,A2,A3;
A1 = temp/100; //百位
A2 = temp%100/10; //十位
A3 = temp%10; //個位
if(flag)
{
w1=0;
P0 =0x40; //用來顯示負(fù)號
delay(1);
w1=1;
P0=0x00;
flag=0;
}
w2=0;
P0 = table[A1]; //顯示百位
delay(10);
w2=1;
P0=0x00;
w3=0;
P0 = table[A2+10]; //顯示十位,使用的是有小數(shù)點的數(shù)組(因為temp值擴大了10倍,雖然是十位,實際為個位)
delay(10);
w3=1;
P0=0x00;
w4=0;
P0 = table[A3]; //顯示個位
delay(10);
w4=1;
P0=0x00;
}
void main()
{
while(1)
{
tmpchange();
Display(Get_Tmp());
}
}