#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit DQ=P3^3;
sbit P20=P2^0;//段选
sbit P21=P2^1;//位选
sbit P35=P3^5;
uint temp;
unsigned char code duan[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
unsigned char code wei[]={0x1,0x2,0x4,0x8,0x10,0x20,0x40,0x80};
uchar tmep[]={0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff};
void init_ds18b20(void);
void delay(uint t);
void write_byte_18(uchar dat);
uchar read_byte_18(void);
uint readtemperature(void);
void display(uchar a,uchar b);
void delay1(uint z)//延时
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void delay_50us(uint t)//延时
{
uchar j;
for(;t>0;t--)
for(j=19;j>0;j--);
}
void main(void)
{
P35=0;
while(1)
{
temp=readtemperature();
tmep[0]=duan[temp/1000];
tmep[1]=duan[(temp/100)%10];
tmep[2]=duan[(temp/10)%10];
tmep[3]=duan[temp%10];
display(0,8);
}
}
void delay(uint t)
{
while(t--);
}
void init_ds18b20(void)//初始化
{
uchar n;
DQ=1;
delay(8);
DQ=0;
delay(80);
DQ=1;
delay(8);
n=DQ;
delay(4);
}
void write_byte_18(uchar dat)//写一个字节
{
uchar i;
for(i=0;i<8;i++)
{
DQ=0;
DQ=dat&0x01;
delay(4);
DQ=1;
dat>>=1;
}
delay(4);
}
uchar read_byte_18(void)//读一个字节
{
uchar i,value;
for(i=0;i<8;i++)
{
DQ=0;
value>>=1;
DQ=1;
if(DQ)
value|=0x80;
delay(4);
}
return value;
}
uint readtemperature(void)
{
uchar a,b;
uint c;
init_ds18b20();
write_byte_18(0xcc); //跳过ROM
write_byte_18(0x44); //启动温度测量
delay(300);
init_ds18b20();
write_byte_18(0xcc);
write_byte_18(0xbe);
a=read_byte_18();
b=read_byte_18();
c=((b*256)+a)*6.25;
return c;
}
void display(uchar a,uchar b)//显示
{
uchar i;
for(i=0;i<b;i++)
{
P1=0xff;
P20=1;
P20=0;
P1=wei[i+a];
P21=1;
P21=0;
P1=tmep[i];
P20=1;
P20=0;
delay1(4);
}
} |