一、树莓派自带W1-GPIO读取
在树莓派中有一种自带的查看DS18B20温度信息,已经写好DS18B20时序,对外设设备进行读取信息然后保存的值在/sys/bus/w1/devices/28-xxxxxxxxxxx/w1_slave文件中,将DS18B20的DQ数据线直接连接在树莓派的GPIO4上就可以使用cat命令进行查看温度值。连接方式如图1,读取温度如图2。读取到温度为 t / 1000,图2的温度为23.187。
图1.使用w1-gpio进行温度读取
图2.使用cat读取温度信息
使用C语言打开w1_slave文件进行读取转换就行,代码如下
#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";
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 fil