51单片机ds18b20.c文件程序
时间: 2023-12-23 20:04:55 浏览: 103
ds18b20通用程序.rar_18b20_ds18b20_ds18b20 51单片机_ds18b20 c程序_ds18b2
以下是51单片机使用ds18b20温度传感器的C语言程序,包含ds18b20.c和ds18b20.h两个文件:
ds18b20.h文件:
```c
#ifndef __DS18B20_H__
#define __DS18B20_H__
#include <reg52.h>
#define DQ P2_1
void Delay1ms();
bit Init_DS18B20();
void Write_DS18B20(unsigned char dat);
unsigned char Read_DS18B20();
unsigned int Read_Temper();
#endif
```
ds18b20.c文件:
```c
#include "ds18b20.h"
void Delay1ms()
{
unsigned char i, j;
for (i = 0; i < 20; i++)
for (j = 0; j < 110; j++);
}
bit Init_DS18B20()
{
bit ack;
DQ = 1;
Delay1ms();
DQ = 0;
Delay1ms();
DQ = 1;
Delay1ms();
ack = DQ;
Delay1ms();
return ack;
}
void Write_DS18B20(unsigned char dat)
{
unsigned char i;
for (i = 0; i < 8; i++)
{
DQ = 0;
DQ = dat & 0x01;
Delay1ms();
DQ = 1;
dat >>= 1;
}
}
unsigned char Read_DS18B20()
{
unsigned char i, dat = 0;
for (i = 0; i < 8; i++)
{
dat >>= 1;
DQ = 0;
DQ = 1;
if (DQ == 1)
dat |= 0x80;
Delay1ms();
}
return dat;
}
unsigned int Read_Temper()
{
bit flag;
unsigned char high, low;
unsigned int tp;
Init_DS18B20();
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
while (!DQ);
Init_DS18B20();
Write_DS18B20(0xcc);
Write_DS18B20(0xbe);
low = Read_DS18B20();
high = Read_DS18B20();
tp = high;
tp <<= 8;
tp |= low;
if (tp & 0x8000)
{
tp = ~tp + 1;
flag = 1;
}
else
flag = 0;
tp *= 0.625;
if (flag)
return -tp;
else
return tp;
}
```
其中,delay1ms()函数是延时函数,Init_DS18B20()函数是初始化函数,Write_DS18B20()函数是写入函数,Read_DS18B20()函数是读取函数,Read_Temper()函数是读取温度函数。使用时只需包含头文件ds18b20.h,调用Read_Temper()函数即可得到温度值。
阅读全文