/*
程序说明: 单总线驱动程序
软件环境: Keil uVision 4.10
硬件环境: CT107单片机综合实训平台(外部晶振12MHz) STC89C52RC单片机
日 期: 2011-8-9
*/
#include "reg52.h"
sbit DQ = P1^4; //单总线接口
//单总线延时函数
void Delay_OneWire(unsigned int t) //STC89C52RC
{
while(t--)
{
_nop_();
_nop_();
_nop_();
_nop_(); //在原有的代码基础上修改为n微秒延时函数
}
}
//通过单总线向DS18B20写一个字节
void Write_DS18B20(unsigned char dat)
{
unsigned char i;
for(i=0;i<8;i++)
{
DQ = 0;
DQ = dat&0x01;
Delay_OneWire(66); //Delay_OneWire(5),原来的已经被注释,修改后的在前面
DQ = 1;
dat >>= 1;
}
Delay_OneWire(5);
}
//从DS18B20读取一个字节
unsigned char Read_DS18B20(void)
{
unsigned char i;
unsigned char dat;
for(i=0;i<8;i++)
{
DQ = 0;
dat >>= 1;
DQ = 1;
Delay_OneWire(4);//(新增)读数据前,一定要加一个延时
if(DQ)
{
dat |= 0x80;
}
Delay_OneWire(66); //Delay_OneWire(5),原来的已经被注释,修改后的在前面
}
return dat;
}
//DS18B20设备初始化
bit init_ds18b20(void)
{
/* bit initflag = 0;
DQ = 1;
Delay_OneWire(12);
DQ = 0;
Delay_OneWire(80);
DQ = 1;
Delay_OneWire(10);
initflag = DQ;
Delay_OneWire(5);
return initflag;
*/
bit initflag = 0;
DQ = 0;
Delay_OneWire(500);
DQ = 1;
Delay_OneWire(80);
initflag = DQ;
return initflag; //初始时序原来的比较复杂,做了整体改动
}
下方这一部分需要自己更具数据手册敲出来,我这里只考虑了正温度,直接在这个函数里面把温度默认为正温度处理,需要处理负温度,按数据手册敲代码。
int fetch_temp()
{
u8 low,high;
int temp;
float tp;
init_ds18b20();
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
Delay_OneWire(660);
init_ds18b20();
Write_DS18B20(0xcc);
Write_DS18B20(0xbe);
Delay_OneWire(660);
low=Read_DS18B20();
high=Read_DS18B20();
temp=high;
temp<<=8;
temp|=low;
tp=temp;
temp=tp*0.0625+0.5;
return temp;
}
.h文件这里就不多说了,比较简单