私のDHTセンサーのライブラリを作成しています。 I AM_2301.cpp
とAM_2301.h
の名前を持つ2つのファイルがあります:私がしたいクラス内でグローバルな別のコンストラクタを呼び出す
#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:
}
しかし、問題がある:
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;
}
とmain.cpp
をのピン番号を宣言するコンストラクタ、そのピンはAM_2301.cpp
の別のコンストラクタに送られますが、実装する方法はわかりません。 dht
オブジェクトを自分のクラス内の他のすべての関数にグローバルにしたいと思っています。
ありがとうございますが、 'AM_2301 :: read()'のように 'AM_2301.cpp'の他の関数でdhtオブジェクトにアクセスするにはどうしたらいいですか? –
あなたと同じ方法です。 –
あなたは正しく私はそれをテストし、答えをここに投稿します。 –