一:DS18B20介绍
DS18B20是常用的数字温度传感器,其输出的是数字信号,具有体积小,硬件开销低,抗干扰能力强,精度高的特点。DS18B20数字温度传感器接线方便,封装成后可应用于多种场合。
二:ds18b20工作原理
DS18B20的读写时序和测温原理与DS1820相同,只是得到的温度值的位数因分辨率不同而不同,且温度转换时的延时时间由2s减为750ms。 DS18B20测温原理如下图所示。图中低温度系数晶振的振荡频率受温度影响很小,用于产生固定频率的脉冲信号发送给计数器1。高温度系数晶振随温度变化其振荡频率明显改变,所产生的信号作为计数器2的脉冲输入。计数器1和温度寄存器被预置在-55℃所对应的一个基数值。计数器1对低温度系数晶振产生的脉冲信号进行减法计数,当计数器1的预置值减到0时,温度寄存器的值将加1,计数器1的预置将重新被装入,计数器1重新开始对低温度系数晶振产生的脉冲信号进行计数,如此循环直到计数器2计数到0时,停止温度寄存器值的累加,此时温度寄存器中的数值即为所测温度。斜率累加器用于补偿和修正测温过程中的非线性,其输出用于修正计数器1的预置值。
三:树莓派连接DS18B20获取温度
1.树莓派的配置
pi@raspberrypi:~ $ sudo raspi-config //打开配置选项
Enter进入后打开1-Wire选项
随后打开内核文件
vim /boot/config.txt
添加引脚连接的引脚
dtoverlay=w1-gpio-pullup,gpiopin=4
sudo reboot //重启树莓派,完成配置
2.示例代码获取温度
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int get_temperature(float *temp);
int main(int argc, char **argv)
{
float temp;
int rv;
rv = get_temperature(&temp);
if(rv < 0)
{
printf("get temperature failure, return value: %d", rv);
return -1;
}
printf("The current temperature: %f\n", temp);
}
int get_temperature(float *temp)
{
int fd = -1;
char buf[128];
char *ptr = NULL;
DIR *dirp = NULL;
struct dirent *direntp = NULL;
char w1_path[64] = "/sys/bus/w1/devices/";
char chip_sn[32];
int found = 0;
dirp = opendir(w1_path);
if( !dirp )
{
printf("open folder %s failure: %sn", w1_path, strerror(errno));
return -1;
}
while( NULL != (direntp = readdir(dirp)) )
{
if( strstr(direntp->d_name, "28-"))
{
strncpy(chip_sn, direntp->d_name, sizeof(chip_sn));
found = 1;
}
}
closedir(dirp);
if( !found )
{
printf("Can not find ds18b20 chipset\n");
return -2;
}
strncat(w1_path, chip_sn, sizeof(w1_path)-strlen(w1_path));
strncat(w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path));
if( (fd = open(w1_path, O_RDONLY)) < 0)
{
printf("open file failure: %s\n", strerror(errno));
return -3;
}
memset(buf, 0, sizeof(buf));
if( read(fd, buf, sizeof(buf)) < 0)
{
printf("read data from fd = %d failure: %s\n", fd, strerror(errno));
return -4;
}
ptr = strstr(buf, "t=");
if( !ptr )
{
printf("Can't find t= string\n");
return -5;
}
ptr += 2;
*temp = atof(ptr)/1000;
close(fd);
return 0;
}