当前位置:网站首页>Raspberry pie 18b20 temperature

Raspberry pie 18b20 temperature

2022-04-23 18:52:00 Brick Porter

One 、 modify /boot/config.txt Add... To the last line dtoverlay=w1-gpio

Or use GUI operation

Plug in the module after shutdown , The default module reads GPIO.7, namely BCM Of 4 foot  , If everything is normal, you can see a 28- Aligned equipment . The temperature value can be obtained by reading the file under a device , I will not go into details here .

#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;
	}
};

The above code needs CPP17 Support .

版权声明
本文为[Brick Porter]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210603257146.html