新手上路
- 积分
- 35
- 金钱
- 35
- 注册时间
- 2014-11-3
- 在线时间
- 0 小时
|
5金钱
//从ds18b20得到温度值
//精度:0.1C
//返回值:温度值 (-550~1250)
//short DS18B20_Get_Temp(void)
//{
// u8 temp;
// u8 TL,TH;
// short tem;
// DS18B20_Start (); // ds1820 start convert
// DS18B20_Rst();
// DS18B20_Check();
// DS18B20_Write_Byte(0xcc);// skip rom
// DS18B20_Write_Byte(0xbe);// convert
// TL=DS18B20_Read_Byte(); // LSB
// TH=DS18B20_Read_Byte(); // MSB
//
// if(TH>7)
// {
// TH=~TH;
// TL=~TL;
// temp=0;//温度为负
// }else temp=1;//温度为正
// tem=TH; //获得高八位
// tem<<=8;
// tem+=TL;//获得底八位
// tem=(float)tem*0.625;//转换
// if(temp)return tem; //返回温度值
// else return -tem;
//}
标红的那几行理解有些问题,我的理解是先读低8位,然后读高8位,是因为DS18B20数字输出的是16位,那么问题来了,我把TH,TL直接用一个16位的变量TT表示,如果TT的最高位为1(不超过32767),temp就为负值,程序如下;
short DS18B20_Get_Temp(void)
{
u8 temp;
// u8 TL,TH;
u16 TT;
short tem;
DS18B20_Start (); // ds1820 start convert
DS18B20_Rst();
DS18B20_Check();
DS18B20_Write_Byte(0xcc);// skip rom
DS18B20_Write_Byte(0xbe);// convert
TT=DS18B20_Read_Byte();
if(TT>32767)
{
TT=~TT;
temp=0;//温度为负
}else temp=1;//温度为正
tem=TT;
tem=(float)tem*0.625;//转换
if(temp)return tem; //返回温度值
else return -tem;
}
编译没问题,但是显示的温度是10度(正常该为23度左右的),小弟初学,不知道对上面的TL,TH理解有没有错,另外请问大神修改后的程序有什么问题吗?
|
|