栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

树莓派获取DS18B20温度数值

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

树莓派获取DS18B20温度数值

代码
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

int Get_FilePath(char *path);    // 获取文件路径
int Get_DS18B20_Temp(double *temp, char *path);
	// 获取温度数值

int main(void)
{
	double	temp;
	char path[50] = "/sys/bus/w1/devices/";  // DS18B20是利用单总线协议进行通讯的,设备都是以文件形式存在
	Get_FilePath(path);   // 获取DS18B20存放温度数据的文件/sys/bus/w1/devices/28-xxxxxx/w1_slave' “28-”后面的DS18B20的序号。
	while(1){

		if (Get_DS18B20_Temp(&temp, path) < 0)
		{
			printf("ERROR: DS18B20 Get Temperature Failuren");
			//return -1;
		}
		printf("Temperature is: %.3f Cn", temp);
		delay(1000);
		delay(1000);	
		delay(1000);			

	}
	return 0;
} 


int Get_FilePath(char *path){

	char			 dir_name[20];
	int				 found = -1;
	DIR 		    *dirp;
	struct dirent	*direntp;

	//清空dir_name内存空间的值,避免随机值产生乱码
	memset(dir_name, 0, sizeof(dir_name));

	//打开文件夹"/sys/bus/w1/devices/"
	if ((dirp = opendir(path)) == NULL)
	{
		printf("ERROR: Open Directory '%s' Failure: %sn", path, strerror(errno));
		return -1;
	}
	printf("Open Directory '%s' Successfullyn", path);
	
	//在文件夹中找DS18B20的文件夹28-xx
	while ((direntp = readdir(dirp)) != NULL)
	{
		if (strstr(direntp->d_name, "28-") == NULL)
			continue;
		
		strncpy(dir_name, direntp->d_name, strlen(direntp->d_name));
		printf("Find file: %sn", dir_name);
		found = 1;
		break;
	}
	closedir(dirp);
	
	//找不到该文件夹
	if (found == -1)
	{
		printf("ERROR: Can not find DS18B20 in %sn", path);
		return -2;
	}
	
	//将文件夹名和文件名分别拼接到path上	
	strncat(path, dir_name, strlen(dir_name));
	strncat(path, "/w1_slave", sizeof(path)-strlen(path));

	return 1;
}




int Get_DS18B20_Temp(double *temp, char *path)
{
	int 			 fd = -1;
	int 			 rv = -1;
	char			*ptr;
	char 			 buf[128];
	
	//清空buf内存空间的值,避免随机值产生乱码
	memset(buf, 0, sizeof(buf));
	//打开w1_slave文件
	if ((fd = open(path, O_RDONLY)) < 0)
	{
		printf("ERROR: Open file '%s' Failure: %sn", path, strerror(errno));
		return -3;
	}
	printf("Open file '%s' fd[%d] Successfullyn", path, fd);
	
	//从w1_slave中读取内容
	if ((rv = read(fd, buf, sizeof(buf))) < 0)
	{
		printf("ERROR: Read data from file '%s' Failure: %sn", path, strerror(errno));
		rv = -4;
		goto cleanup;
	}
	printf("Read %dB data from file '%s'n", rv, path);
	
	//从buf里匹配"t=",并将ptr移到数据的首地址上
	if ((ptr = strstr(buf, "t=") + 2) == NULL)
	{
		printf("ERROR: Find data Failure: %s", strerror(errno));
		rv = -5;
		goto cleanup;
	}
	
	//将数据转为double型,除1000得到正常的十进制温度
	*temp = atof(ptr)/1000;

cleanup:
	if (fd > 0)
		close(fd);

	return rv;
}

使能树莓派内核的单总线协议驱动模块(1-Wire)

【C语言】树莓派(Raspberry Pi)+DS18B20 获取当前温度

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/780035.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号