#include
#include
sbit DQ=P2^7;
unsigned char tem=0;
unsigned char s[]={0x3f,0x06,0x5b,0x4f,0x66,
0x6d,0x7d,0x07,0x7f,0x67};//共阴极0~9
unsigned char ss[]={0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,0x87,0xff,0xef};//共阴极0~9带小数点
unsigned char d[]={0xff.0xfe,0xfd,0xfd,0xf7};//片选
void delay_18B20(unsigned int i)//微秒级
{
for(;i>0;i--);
}
void show(unsigned char tem)
{
unsigned char t1=0,t2=0,t3=0;
t1=tem/100;
t2=(tem%100)/10;
t3=tem%10;
P2=d[0];
P0=s[t1];
P2=d[1];
delay(10);
P2=d[0];
P0=s[t1];
P2=d[1];
delay(10);
P2=d[0];
P0=s[t2];
P2=d[2];
delay(10);
P2=d[0];
P0=ss[t3];
P2=d[3];
delay(10);
P2=d[0];
P0=s[0];
P2=d[4];
delay(10);
}
unsigned char ReadoneChar(void)//读程序
{
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(4);
}
return(dat);
}
void Init_18B20(void)//初始化
{
unsigned char x=0;
DQ = 1; //DQ拉高
delay_18B20(8); //延时//可省略
DQ = 0; //DQ拉低
delay_18B20(80); //延时>480us
DQ = 1; //拉高总线
delay_18B20(14); //延时60-75us,
x=DQ; //若x=0 初始化成功,否则失败
delay_18B20(20); //至少延时480us
}
void WriteOneChar(unsigned char dat)//写操作
{
unsigned char i=0;
for (i=8;i>0;i--)
if(DQ)
{
dealy_18B20(1);
DQ=1;
else
{
delay_18B20(5);
DQ=1;
dat>>1;
}
}
unsigned char ReadTemperture(void)//读温度
{
unsigned char a=0,b=0,temp=0;
Init_DS18B20();
writeoneChar(0xCC);//跳过读序列号操作
writeoneChar(0x44);//启动温度转换
delay_18B20(100); //
Init_DS18B20();
writeoneChar(0xCC);//跳过读序列号操作
writeoneChar(0xBE);//读取温度寄存器
delay_18B20(100);
a=ReadOneChar(); //读温度低位
b=ReadOneChar(); //读温度高位
temp=((b*256+a)>>4);//当前采集温度除以16得到实际温度
return(temp);
}
}
void main()
{
while(1)
{
tem=ReadTemperture();
show(tem);
}
}