STC89C52RC单片机DS18B20温度传感器驱动程序代码
#include 'onewire.h'
sbit DQ = P1^0; //单总线接口
//单总线延时函数 void Delay_OneWire(unsigned int t) //STC89C52RC { while(t--); // 等待t个时钟周期 }
//通过单总线向DS18B20写一个字节 void Write_DS18B20(unsigned char dat) { unsigned char i; for(i=0;i<8;i++) { DQ = 0; // 拉低总线 DQ = dat&0x01; // 写入数据的最低位 Delay_OneWire(5); // 延时5个时钟周期 DQ = 1; // 释放总线 dat >>= 1; // 数据右移一位,准备写入下一位 } Delay_OneWire(5); // 延时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; // 释放总线
if(DQ)
{
dat |= 0x80; // 如果总线为高电平,则将最高位置1
}
Delay_OneWire(5); // 延时5个时钟周期
}
return dat;
}
//DS18B20设备初始化 // 返回值为初始化状态,如果为0则初始化成功,否则失败 bit init_ds18b20(void) { bit initflag = 0;
DQ = 1; // 释放总线
Delay_OneWire(12); // 延时12个时钟周期
DQ = 0; // 拉低总线
Delay_OneWire(80); // 延时80个时钟周期
DQ = 1; // 释放总线
Delay_OneWire(10); // 延时10个时钟周期
initflag = DQ; // 读取总线状态,如果为高电平则初始化失败
Delay_OneWire(5); // 延时5个时钟周期
return initflag;
}
原文地址: https://www.cveoy.top/t/topic/o1me 著作权归作者所有。请勿转载和采集!