Ich erstellen eine Bibliothek für meinen DHT-Sensor. Ich habe 2 Dateien mit Namen von AM_2301.cpp
und AM_2301.h
:Rufen Sie einen anderen Konstruktor als global innerhalb einer Klasse
AM_2301.h
:
#ifndef AM2301_h
#define AM2301_h
#include "Arduino.h"
struct Two_float {
float temp;
float humidity;
};
extern int pinn;
class AM_2301
{
public:
AM_2301(int pin);
void begin();
struct Two_float read();
private:
int _pin;
};
#endif
AM_2301.cpp
:
#include "Arduino.h"
#include "AM_2301.h"
#include "DHT.h"
//#define pinn 3
int pinn;
DHT dht(pinn, DHT21);
AM_2301::AM_2301(int pin)
{
pinMode(pin, OUTPUT);
Serial.print("pinn: ");
Serial.println(pinn);
_pin = pin;
pinn = pin;
//DHT dht(pinn, DHT21);
}
void AM_2301::begin(){
dht.begin();
}
struct Two_float AM_2301::read()
{
struct Two_float output;
float h = dht.readHumidity();
float t = dht.readTemperature();
// check if returns are valid, if they are NaN (not a number) then something went wrong!
if (isnan(t) || isnan(h))
{
Serial.println("Failed to read from DHT");
t = 0;
h = 0;
}
output = {t, h};
return output;
}
und main.cpp
:
#include "Arduino.h"
#include "AM_2301.h"
int pin =3 ;
AM_2301 AM(pin);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
AM.begin();
}
void loop() {
struct Two_float val;
val = AM.read();
Serial.print("Temp: ");
Serial.print(val.temp);
Serial.print(" , ");
Serial.print("Humidity: ");
Serial.println(val.humidity);
delay(2000);
// put your main code here, to run repeatedly:
}
Aber das Problem ist, ich will deklariere eine Pin-Nummer in der Konstruktor, und dieser Pin geht zu einem anderen Konstruktor in AM_2301.cpp
, aber ich weiß nicht, wie das zu implementieren ist. Ich möchte dht
Objekt machen, um zu allen anderen Funktionen innerhalb meiner Klasse global zu werden.
Danke, aber wie kann ich auf dht Objekt in anderen Funktionen in 'AM_2301.cpp' wie' AM_2301 :: read() 'zugreifen? –
So wie Sie bereits tun. –
Sie haben Recht Ich teste es und posten Sie die Antwort hier. –