Proteus 仿真运行结果如下:
DS18B20的应用实例二
#include《reg51.h》
sbit DQ=P3^0;
sbit d1=P2^0;
sbit d2=P2^1;
#define uchar unsigned char
#define uint unsigned int
uchar temp_value;
uchar code table[]={0X3F,0X06,0X5B,0X4F,0X66,0X6D,0X7D,0X07,0X7F,0X6F};
void delay_18B20(uint i)
{
while(i--);
}
void Init_DS18B20(void)
{
uchar x=0;
DQ = 1; //DQ复位
delay_18B20(8); //稍做延时
DQ = 0; //单片机将DQ拉低
delay_18B20(80); //精确延时 大于 480us
DQ = 1; //拉高总线
delay_18B20(14);
x=DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
delay_18B20(20);
}
uchar ReadOneChar(void)
{
uchar i=0;
uchar dat = 0;
for (i=8;i》0;i--)
{
DQ = 0; // 给脉冲信号
dat》》=1;
DQ = 1; // 给脉冲信号
if(DQ)
dat|=0x80;
delay_18B20(4);
}
return(dat);
}
void WriteOneChar(uchar dat)
{
uchar i=0;
for (i=8; i》0; i--)
{
DQ = 0;
DQ = dat&0x01;
delay_18B20(5);
DQ = 1;
dat》》=1;
}
}
void ReadTemp(void)
{
uchar a=0;
uchar b=0;
uchar t=0;
Init_DS18B20();
WriteOneChar(0xCC); // 跳过读序号列号的操作
WriteOneChar(0x44); // 启动温度转换
delay_18B20(100); // this message is wery important
Init_DS18B20();
WriteOneChar(0xCC); //跳过读序号列号的操作
WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
delay_18B20(100);
a=ReadOneChar(); //读取温度值低位
b=ReadOneChar(); //读取温度值高位
temp_value=b《《4;
temp_value+=(a&0xf0)》》4;
}
void display (uchar num0,uchar num1)
{ P2=0XFD;
P0=table[num1];
delay_18B20(20);
P2=0XFE;
P0=table[num0];
delay_18B20(20);
}
main()
{
uchar a ,b ;
while(1)
{
ReadTemp();
b=temp_value/10; //十位
a=temp_value%10; //个位
display(b,a);
}
}