原标题:51单片机 8255 18b20 数码管显示温度C程序
date = 0;
i = 100; //拉低约900us
while (i>0) i--;
date= 1; // 产生上升沿
i = 4;
while (i>0) i--;
}
void wait()
{
uint i;
while(date);
while(~date); // 检测到应答脉冲
i = 4;
while (i>0) i--;
}
bit readbit()
{
uint i;
bit b;
date = 0;
i++;
date = 1;
i++;i++; // 延时15us以上,读时隙下降沿后15us,DS18B20输出数据才有效
b = date;
i = 8;
while(i>0) i--;
return (b);
}
uchar readbyte()
{
uchar i,j,b;
b = 0;
for (i=1;i<=8;i++)
{
j = readbit();
b = (j<<7)|(b>>1);//读出的数据最低位在最前面,这样刚好一个字节在DATE里
}
return(b);
}
void writebyte(uchar b)//
{
uint i;
uchar j;
bit btmp;
for(j=1;j<=8;j++)
{
btmp = b&0x01;
b = b>>1; // 取下一位(由低位向高位)
if (btmp) // 写1
{
date = 0;
i++;i++; // 延时,使得15us以内拉高
date = 1;
i = 8;
while(i>0) i--; // 整个写1时隙不低于60us
}
else // 写0
{
date = 0;
i = 8;
while(i>0) i--; // 保持低在60us到120us之间
date = 1;
i++;
i++;
}
}
}
void convert()
{
init(); // 产生复位脉冲,初始化DS18B20
wait(); // 等待DS18B20给出应答脉冲
delay(1); // 延时
writebyte(0xcc); // 跳过rom 命令
writebyte(0x44); // convert T 命令
}
uint readtemp()
{
float tt;
init(); // 产生复位脉冲,初始化DS18B20
wait(); // 等待DS18B20给出应答脉冲
delay(1); // 延时
writebyte(0xcc); // 跳过rom命令
writebyte(0xbe); // read scratchpad 读暂存器命令
tplsb=readbyte(); // 温度值低位字节(其中低4位为二进制的"小数"部分)
tpmsb=readbyte(); // 温度值高位字节(其中高5位为符号位)
temp=tpmsb;
temp<<=8; //合成一个字
temp=temp|tplsb;
tt=temp*0.0625;
temp=tt*10+0.5;
return temp;
责任编辑: