gpt4 book ai didi

c++ - 在类中调用另一个构造函数作为全局

转载 作者:行者123 更新时间:2023-11-27 22:42:32 27 4
gpt4 key购买 nike

<分区>

我正在为我的 DHT 传感器创建一个库。我有 2 个文件,名称分别为 AM_2301.cppAM_2301.h:

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:

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

但问题是我想在构造函数中声明一个 pin 编号,该 pin 转到 AM_2301.cpp 中的另一个构造函数,但我不知道如何实现它。我想让 dht 对象成为我类中所有其他函数的全局对象。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com