#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit DS=P3^7; //define interface
uint temp; // variable of temperature
/*uchar flag1; // sign of the result positive or negative*/
sbit A2=P2^2;
sbit B2=P2^3;
sbit C2=P2^4;
unsigned char code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,
0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
unsigned char code table1[]={0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,
0x87,0xff,0xef};
void delay(uint xms) //delay
{
uint a,b;
for(a=xms;a>0;a--)
for(b=110;b>0;b--);
}
void dsreset(void) //send reset and initialization command 18B20复位,初始化函数
{
uint i;
DS=0;
i=103;
while(i>0)i--;
DS=1;
i=4;
while(i>0)i--;
}
bit tmpreadbit(void) //read a bit 读1位数据函数
{
uint i;
bit dat;
DS=0;i++; //i++ for delay
DS=1;i++;i++;
dat=DS;
i=8;while(i>0)i--;
return (dat);
}
uchar tmpread(void) //read a byte date 读1字节函数
{
uchar i,j,dat;
dat=0;
for(i=1;i<=8;i++)
{
j=tmpreadbit();
dat=(j<<7)|(dat>>1); //读出的数据最低位在最前面,这样刚好一个字节在DAT里
}
return(dat);
}
void tmpwritebyte(uchar dat) //write a byte to ds18b20 向1820写一个字节数据函数
{
uint i;
uchar j;
bit testb;
for(j=1;j<=8;j++)
{
testb=dat&0x01;
dat=dat>>1;
if(testb) //write 1
{
DS=0;
i++;i++;
DS=1;
i=8;while(i>0)i--;
}
else
{
DS=0; //write 0
i=8;while(i>0)i--;
DS=1;
i++;i++;
}
}
}
void tmpchange(void) //DS18B20 begin change 开始获取数据并转换
{
dsreset();
delay(1);
tmpwritebyte(0xcc); // address all drivers on bus 写跳过读ROM指令
tmpwritebyte(0x44); // initiates a single temperature conversion 写温度转换指令
}
uint tmp() //get the temperature 读取寄存器中存储的温度数据
{
float tt;
uchar a,b;
dsreset();
delay(1);
tmpwritebyte(0xcc);
tmpwritebyte(0xbe);
a=tmpread(); //读低8位
b=tmpread(); //读高8位
temp=b;
temp<<=8; //two byte compose a int variable 两个字节组合为1个字
temp=temp|a;
tt=temp*0.0625; //温度在寄存器中是12位,分辨率是0.0625
temp=tt*10+0.5; //乘10表示小数点后只取1位,加0.5是四折五入
return temp;
}
void display(uint temp) //显示程序
{
uchar bai,shi,ge,A1;
bai=temp/100;
A1=temp%100;
shi=A1/10;
ge=A1%10;
A2=0;B2=0;C2=0;
P0=table[bai]; //显示百位
delay(5);
A2=1;B2=0;C2=0;
P0=table1[shi]; //显示十位
delay(5);
A2=0;B2=1;C2=0;
P0=table[ge];
delay(5); //显示十位
}
void main()
{
while(1)
{
tmpchange();
display(tmp());
}
}