树莓派DS18B20温度传感器获取温度

本文详细介绍了如何在树莓派上启用DS18B20温度传感器,包括使用`sudorspi-config`配置、重启、查看模块支持以及通过C语言程序读取实时温度。适合对单总线协议和嵌入式开发感兴趣的读者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

树莓派使能DS18B20

 C程序获取DS18B20温度


树莓派使能DS18B20

sudo raspi-config 进行配置树莓派,启动1-Wire完成使能

 

 

sudo reboot  重启树莓派,使其完成配置 

lsmod | grep w1命令可以查看当前系统支持的单总线协议模块

(lsmod(list modules)命令用于显示已载入系统的模块)

cd /sys/bus/w1/devices/28-xxxxxxxxx(这是设备特定序列号)

cat w1_slave 即可查看DS18B20测量的温度值


 

 C程序获取DS18B20温度

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.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("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 not find t= string\n");
		return -5;
	}

	ptr += 2;

	*temp = atof(ptr)/1000;

	close(fd);

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值