我从OOP的角度为C++写了一个Arduino的程序,并遇到了一个问题:类的方法无法看到该类的构造函数中定义的对象。我试图完成的是创建一个对象(类),用于容纳各种用于计算和输出来自传感器的数据的方法。 全码:对象内的C++对象
* DhtSensor.h
*
* Created on: 2017-04-18
* Author: Secret
*/
#ifndef DhtSensor_h
#define DhtSensor_h
class DhtSensor {
public:
DhtSensor(int dhtPin); //constructor
void read();
void printToScreen(); //a method for printing to LCD
private:
unsigned long previousMillis; //Millis() of last reading
const long readInterval = 3000; //How often we take readings
float readingData[2][30]; //store current ant last values of temperature [0] and humidity [1] readings
int readingIndex;
bool initDone; //Bool value to check if initialization has been complete (Array full)
float totalTemp;
float totalHumidity;
float avgTemp;
float avgHumidity;
float hic; //Heat Index
};
#endif
/*
* DhtSensor.cpp
*
* Created on: 2017-04-18
* Author: Secret
*/
#include "DhtSensor.h"
#include "DHT.h"
#include "Arduino.h"
DhtSensor::DhtSensor(int dhtPin){
DHT dht(dhtPin,DHT11);
dht.begin();
previousMillis = 0;
totalTemp = avgTemp = 0;
totalHumidity = avgHumidity = 0;
hic = 0;
readingIndex = 0;
initDone = false;
for(int i = 0; i<2; i++){ //matrix init
for(int j=0; j<30; j++){
readingData[i][j]=0;
}
}
}
void DhtSensor::read(){
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= readInterval){
readingData[0][readingIndex] = dht.readTemperature();
}
}
在的.cpp文件read()
方法中,会出现问题。它没有看到在构造函数中创建的对象dht
。 我在这里错过了什么?这是甚至是一个很好的做法,在对象内部有对象吗?也许我应该从DhtSensor
类中排除DHT
库,并在主类中创建一个DHT
对象,我将使用库的方法将数据发送到DhtSensor
?
您可能想让实例成为您的类的成员,而不是函数的一部分。 – JVApen
在开始使用一种语言之前,你确实需要阅读一本关于C++的书。使用C++进行尝试和错误是非常痛苦的,通常不会带来好的结果。 – SergeyA