一、修改/boot/config.txt最后一行加上 dtoverlay=w1-gpio
或者使用GUI操作
关机以后插上模块,默认模块读取为GPIO.7,即BCM的4脚 ,如果一切正常则可以在这个路径下看到一个28-开对的设备。读取个设备下的文件即可获取温度值,此处不再细说。
#pragma once
#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
class CDTH22
{
public:
static std::string GetTemp()
{
std::string ret;
fs::path str("/sys/bus/w1/devices");
if (!fs::exists(str))
return ret;
fs::directory_entry entry(str);
if (entry.status().type() == fs::file_type::directory)
{
fs::directory_iterator list(str);
for (auto& it : list)
{
if (it.is_directory()&&(it.path().filename().string().find("28-")==0))
{
std::ifstream tfile(it.path().string()+"/w1_slave");
if (tfile.is_open())
{
std::string buf;
std::getline(tfile,buf);
//CRC ok
if (buf.rfind("YES") != std::string::npos)
{
std::getline(tfile, buf);
std::size_t pos=buf.rfind("t=");
if(pos!= std::string::npos)
try {
ret=std::to_string(std::atoi(buf.data() + pos + 2)/1000);
}
catch (...)
{
}
}
}
}
}
}
return ret;
}
};
上面代码需要CPP17支持。