adafruit / DHT-sensor-library

Arduino library for DHT11, DHT22, etc Temperature & Humidity Sensors
https://learn.adafruit.com/dht
MIT License
1.97k stars 1.43k forks source link

define an empty constructor and overload DHT::begin #196

Open edWin-m opened 1 year ago

edWin-m commented 1 year ago

The use of an empty constructor allows for some more complex and flexible initialization logic without the need to write out every step explicitly.

caternuson commented 1 year ago

Can you provide more information on why this is necessary? What's an example use case that requires this empty constructor?

edWin-m commented 1 year ago

@caternuson An empty constructor will allow users to define an instance of DHT as a member of their classes. Furthermore, it grants users more options on how and at what stage of their program logic they can set the library config.

Use Case One

DHT dht;

void setup()
{
    dht.begin(D7, DHT11);
}

void loop()
{
    ...
    float humidity = dht.readHumidity();
    ...
}

Use Case Two

class MySensor {
public:
    MySensor();
    MySensor(uint8_t pin);
    void begin();
    void begin(uint8_t pin);
    ...
private:
    ...
    DHT dht;
    ...
};

Use Case Three

void my_sensor_loop();
void my_sensor_setup(uint8_t data_pin, sensor_callback_t cb_func);
...
static DHT sg_dht;
...

void my_sensor_setup(uint8_t data_pin, sensor_callback_t cb_func)
{
    ...
    sg_callback = cb_func;
    sg_dht.begin(data_pin, DHT11);
    ...
}

void my_sensor_loop()
{
    ...
    float humidity = sg_dht.readHumidity();
    float temperature = sg_dht.readTemperature();
    ...
}