0
votes

I am working on a smart greenhouse project using an ESP32 as a microcontroller.

Data comes from a DHT22 temperature and humidity sensor and a soil moisture sensor. Those two tend to use delay() functions to read, because they need some time to warm up.

Example:

    void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
}

I am planning on posting this data on a web interface, which would have manual controls available too. Since I am using delays, if I press the button on the website, first the delay executes, then the button press, so it's not instant. What could I do to fix that?

1
Just display a message that says "Warming up..." - Chris Catignani

1 Answers

0
votes

Don't use delay(). I'm not clear on exactly what you're trying to do here or how you're trying to handle the button, but in general you're better off doing something like this:

#define SENSOR_UPDATE_WARMUP 2000
#define SENSOR_UPDATE_INTERVAL 1000

void loop() {
  static unsigned long next_sensor_update = SENSOR_UPDATE_WARMUP;

  if(millis() > next_sensor_update) {
    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.readHumidity();
    // Read temperature as Celsius (the default)
    float t = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    float f = dht.readTemperature(true);

    next_sensor_update = millis() + SENSOR_UPDATE_INTERVAL;
    }
}

This allows you to other processing in loop() while still having the warmup time and only updating the sensor readings periodically (adjust SENSOR_UPDATE_INTERVAL to the number of milliseconds between updates).

If you need to have other delays for other devices just repeat the pattern of having a static variable that tracks the timing for those devices.

Even simpler, you could just put the two second delay at the end of setup() rather than inside loop(), but I suspect you're not going to want to update the sensor values constantly, so you'll want to structure your program similarly to the code above.