基于stc89c52的ds18b20的库函数
时间: 2023-11-20 22:07:25 浏览: 36
以下是基于STC89C52单片机的DS18B20的库函数示例:
```c
#include <reg52.h>
#include <intrins.h>
typedef unsigned char uchar;
typedef unsigned int uint;
sbit DQ = P2^0;
void Delay1ms(uint);
void Delay10us(uint);
uchar Ds18b20Init();
uchar Ds18b20ReadByte();
void Ds18b20WriteByte(uchar dat);
int Ds18b20ReadTemp();
void main()
{
int temp;
while(1)
{
temp = Ds18b20ReadTemp();
if(temp != -1)
//输出温度值
}
}
void Delay1ms(uint i)
{
uchar j;
while(i--)
{
j = 12;
while(j--);
}
}
void Delay10us(uint i)
{
while(i--)
{
_nop_();
_nop_();
}
}
uchar Ds18b20Init()
{
uchar i;
DQ = 1;
Delay10us(1);
DQ = 0;
Delay10us(80);
DQ = 1;
Delay10us(5);
i = DQ;
Delay10us(20);
return i;
}
uchar Ds18b20ReadByte()
{
uchar i, dat = 0;
for(i=0; i<8; i++)
{
DQ = 0;
_nop_();
_nop_();
dat >>= 1;
DQ = 1;
_nop_();
_nop_();
if(DQ)
dat |= 0x80;
Delay10us(4);
}
return dat;
}
void Ds18b20WriteByte(uchar dat)
{
uchar i;
for(i=0; i<8; i++)
{
DQ = 0;
_nop_();
_nop_();
DQ = dat & 0x01;
dat >>= 1;
_nop_();
_nop_();
DQ = 1;
Delay10us(4);
}
}
int Ds18b20ReadTemp()
{
uchar a, b;
int temp;
if(!Ds18b20Init())
return -1;
Ds18b20WriteByte(0xcc);
Ds18b20WriteByte(0x44);
Delay1ms(500);
if(!Ds18b20Init())
return -1;
Ds18b20WriteByte(0xcc);
Ds18b20WriteByte(0xbe);
a = Ds18b20ReadByte();
b = Ds18b20ReadByte();
temp = b;
temp <<= 8;
temp |= a;
temp = (float)temp * 0.0625 * 10 + 0.5;
return temp;
}
```
这里定义了几个常用的函数,如延时函数、初始化函数、读写字节函数、读取温度函数。在主函数中可以调用读取温度函数,获取温度值并进行相应的处理。请注意,这里的温度值最后以10倍的整数形式返回,以保留一位小数。如果需要更高的精度,可以修改相应的部分。