TransWikia.com

Instantiate class in the constructor rather in the top end?

Arduino Asked by Socrates on September 25, 2021

Is there a way to define class variables in the constructor or in a method rather than at the top of the document?

I have the following code in my custom library:

#include "DHT.h"

// DHT settings.
#define DHTPIN 7 // Digital pin connected to the DHT sensor.
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.

void DhtLib::doSomeStuff() {
  dht.begin();
  float temp = dht.readTemperature();
  ...
}

I would like to be able to set the pins with a function. But for this to work I have to find a way to define the dht variable in a different place than at the top of the document within the // DHT settings.. Best would be in a method such as:

void DhtLib::begin(int dhtPin) {
  DHT dht(dhtPin, DHTTYPE);
}

This works, but only within this function. I need this to be accessible in the entire document, not just a single function.

How can I achieve that?

EDIT 1:

Entire code of the custom DhtLibrary.h file:

#ifndef DhtLibrary_h
#define DhtLibrary_h

#if (ARDUINO >= 100)
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

class DhtLib {
  private:
    DHT dht;
    float readTemperatureFromDHT();
    float readHumidityFromDHT();
    float calculateHeatIndex(float temperature, float humidity);
    
  public:
    // Constructor.
    DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}

    // Methods.
    void begin();
    String getHumiTempJson();
};

#endif

The error with this above code is:

In file included from /home/myuser/Documents/Codes/temperature-control/slave2-arduino/slave2-arduino.ino:2:0:
DhtLibrary.h:12:5: error: 'DHT' does not name a type
     DHT dht;

One Answer

There's numerous ways of doing this. The best is probably to have a DHT object as a class property and set it up with an initializer list:

#include "DHT.h"

class DhtLib {
    private:
        DHT dht;

    public:
        DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}
        void begin();
        void doSomeStuff();
};

void DhtLib::begin() {
    dht.begin();
}

void DhtLib::doSomeStuff() {
    float temp = dht.readTemperature();
}

DhtLib thing(7);

void setup() {
    thing.begin();
}

void loop() {
    thing.doSomeStuff();
}

Correct answer by Majenko on September 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP