【树莓派】DS18B20温度传感器

1、接线按照下图:“-”号接地,中间接VCC电压(3.3v或者5v),S接口接GPIO4(Pin接口的7,BCM的4,wiringPi的7);

在这里插入图片描述必须设置:
在/boot/config.txt最下面,设置S接口接GPIO4
dtoverlay=w1-gpio-pullup,gpiopin=4

2、转移到驱动所在得目录。

sudo modprobe w1-gpio
sudo modprobe w1-therm
cd /sys/bus/w1/devices
ls
cd 28-xxxx (change this to match what serial number pops up)
cat w1_slave

3、循环读取温度temp.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>

#define  BUFSIZE  128

char* addr = "/sys/bus/w1/devices/28-02161682f4ee/w1_slave";# 28-02161682f4ee是你的文件夹名字需要修改

int main(void)
{
	float temp;
	int i, j;
    int fd;
	int ret;

	char buf[BUFSIZE];
	char tempBuf[5];
	while (1){
	fd = open(addr, O_RDONLY);

	if(-1 == fd){
		perror("open device file error");
		return 1;
	}

	while(1){
		ret = read(fd, buf, BUFSIZE);
		if(0 == ret){
			break;	
		}
		if(-1 == ret){
			if(errno == EINTR){
				continue;	
			}
			perror("read()");
			close(fd);
			return 1;
		}
	}

	for(i=0;i<sizeof(buf);i++){
		if(buf[i] == 't'){
			for(j=0;j<sizeof(tempBuf);j++){
				tempBuf[j] = buf[i+2+j]; 	
			}
		}	
	}

	temp = (float)atoi(tempBuf) / 1000;

	printf("%.3f C\n",temp);

	close(fd);
	}
	return 0;
}

5、gcc编译

gcc temp.c -o temp -lwiringPi

6、终端运行

./temp
发布了146 篇原创文章 · 获赞 60 · 访问量 28万+

猜你喜欢

转载自blog.csdn.net/xiaoxiao133/article/details/92984019
今日推荐