#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
uchar SegBuffer[4]={0};
unsigned char code SegCode[11]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,
0x07,0x7f,0x6f,0x40};
unsigned char code SegCode_d[10]={0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,
0x87,0xff,0xef};
sbit DS=P2^2;
sbit dula=P2^6;
sbit wela=P2^7;
void Delay_15us(uint temp)
{
for(temp; temp>0;temp--)
{
_nop_();
_nop_();
_nop_();
_nop_();
}
_nop_();
_nop_();
}
void Delay_1ms(uint i)
{
uchar x,j;
for(j=0;j<i;j++)
for(x=0;x<=148;x++);
}
void RST_DS18B20()
{
bit ret=1;
DS=0;
Delay_15us(39);
DS=1;
Delay_15us(4);
ret=DS;
Delay_15us(27);
DS=1;
}
void WBIT_DS18B20(bit data_bit)
{
DS=0;
Delay_15us(0);
DS=data_bit;
Delay_15us(2);
DS=1;
}
bit RBIT_DS18B20(void)
{
bit data_bit;
DS=0;
_nop_();
_nop_();
_nop_();
DS=1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
data_bit=DS;
Delay_15us(3);
DS=1;
return data_bit;
}
void WBYTE_DS18B20(uchar data_byte)
{
uchar i;
for(i=0;i<8;i++)
{
WBIT_DS18B20(data_byte&0x01);
data_byte>>=1;
}
}
uchar RBYTE_DS18B20(void)
{
uchar data_byte=0;
uchar i,j;
for(i=0;i<8;i++)
{
j=RBIT_DS18B20();
j=j<<i;
data_byte= data_byte|j;
}
return data_byte;
}
void START_DS18B20(void)
{
DS=1;
_nop_();
_nop_();
RST_DS18B20();
WBYTE_DS18B20(0xCC);
WBYTE_DS18B20(0x44);
}
uint READ_TEM(void)
{
uint tem=0;
DS=1;
_nop_();
_nop_();
RST_DS18B20();
WBYTE_DS18B20(0xCC);
WBYTE_DS18B20(0xbe);
tem=RBYTE_DS18B20();
tem=(RBYTE_DS18B20()<<8)|tem;
return tem;
}
void Temperature_4(uint data_tem)
{
uint dat=0;
float temp;
if(data_tem&0x0800)
{
data_tem=~data_tem+1;
temp=data_tem*0.0625;
temp=temp*10+0.5;
dat=temp;
SegBuffer[0]=SegCode[dat%10];
SegBuffer[1]=SegCode_d[dat/10%10];
SegBuffer[2]=SegCode[dat/100%10];
SegBuffer[3]=SegCode[10];
}
else
{
temp=data_tem*0.0625;
temp=temp*10+0.5;
dat=temp;
SegBuffer[0]=SegCode[dat%10];
SegBuffer[1]=SegCode_d[dat/10%10];
SegBuffer[2]=SegCode[dat/100%10];
SegBuffer[3]=SegCode[dat/1000%10];
}
}
void Segdisplay(void)
{
dula=0;
P0=SegBuffer[0];
dula=1;
dula=0;
wela=0;
P0=0xf7;
wela=1;
wela=0;
Delay_1ms(3);
dula=0;
P0=SegBuffer[1];
dula=1;
dula=0;
wela=0;
P0=0xfb;
wela=1;
wela=0;
Delay_1ms(3);
dula=0;
P0=SegBuffer[2];
dula=1;
dula=0;
wela=0;
P0=0xfd;
wela=1;
wela=0;
Delay_1ms(3);
dula=0;
P0=SegBuffer[3];
dula=1;
dula=0;
wela=0;
P0=0xfe;
wela=1;
wela=0;
Delay_1ms(3);
}
void main()
{
uint temp=0;
while(1)
{
START_DS18B20();
temp=READ_TEM();
Temperature_4(temp);
Segdisplay();
}
}