【发布时间】:2021-01-31 11:24:09
【问题描述】:
我尝试编写一个小程序来控制与树莓派 3B+ 上的两个 ds18b20 温度传感器连接的泵和阀门。我为泵和阀门定义了一个类,将来会添加更多的泵和阀门,我还为通过 1 根电线连接的 ds18b20 传感器创建了一个类。传感器可以通过“文件”读取,因此有一个基本目录string baseDir = "/sys/bus/w1/devices/";,后跟设备IDstring tSensor1 = "28-3c01a81688f4";和温度“文件”string tempFile = "/w1_slave";,完整路径应如下所示/sys/bus/w1/devices/28-3c01a81688f4/w1_slave。
但我得到的是这个TestSensor1= Error reading file at /sys/bus/w1/devices//w1_slave 设备丢失,TestSensor2= Error reading file at /sys/bus/w1/devices//w1_slave 也是如此。
代码直接在rPi上编译,g++ -Wall -o oww ofen-warmwasser.cpp -lwiringPi
这是我的代码
#include <wiringPi.h> // library to access the GPIO Pins on a raspberryPI !!deprecated!!
#include <iostream> // cout
#include <fstream> // file stream access
#include <string> // string class
#include <sstream> // string stream needed for file access to put data into string
//... code skipped ...
class temperaturSensor {
private:
string device;
string baseDir = "/sys/bus/w1/devices/";
string tempFile = "/w1_slave";
string path = baseDir + device + tempFile;
stringstream buffer;
string data;
string strTemp;
double temp = 987.6;
public:
// constructor declaration
temperaturSensor(string str);
// methodes
double temperatur() {
//cout << "----->>>> " << device << " ----->>>> " << path << endl;
ifstream infile(path);
if (infile) {
buffer << infile.rdbuf();
data = buffer.str();
infile.close();
}
else {
infile.close();
cout << "Error reading file at " << path << endl;
return -100;
}
size_t crcCheck = data.find("YES");
if (crcCheck == string::npos) {
cout << "CRC fail not reading temperatur" << endl;
return -101;
}
size_t TempPos = data.find("t=");
if (TempPos == string::npos) {
cout << "failed to find value -> abort!" << endl;
return -102;
}
strTemp = data.substr(TempPos+2);
temp = stod(strTemp)/1000;
return temp;
}
};
// constructor
temperaturSensor::temperaturSensor(string str) {
device = str;
}
int main(void) {
// test setup
pump boilerpumpe(21);
valve boilervalve(28);
string tSensor1 = "28-3c01a81688f4";
temperaturSensor testSensor1(tSensor1);
temperaturSensor testSensor2("28-3c01a816d9c1");
while (true)
{
boilerpumpe.on();
boilervalve.close();
cout << "TestSensor1= " << testSensor1.temperatur() << "°C \nTestSensor2= " << testSensor2.temperatur() << "°C" << endl;
delay(5*1000);
boilerpumpe.off();
boilervalve.open();
delay(5*1000);
}
return 0;
}
正如您在代码中看到的那样,我尝试了不同的方法,从将 string device; 变量从 private: 声明到 public: 从类的末尾到开头,当我 cout 设备变量时,它会正确显示,我认为问题出在string path = baseDir + device + tempFile;,我也尝试过string path = baseDir.append(device);,但没有成功
感谢任何帮助,如果需要更多信息,请告诉我什么,我会尽力提供
感谢蚀刻
【问题讨论】:
-
在为
device设置值之前,您正在初始化path的值。不要尝试为path设置值,直到您知道它实际上是什么,即在构造函数中。 -
@NathanPierson 谢谢你说得通
标签: c++ string class raspberry-pi concatenation