Home > database >  Time dependent data acquisition from DHT22 - problem with initial loops
Time dependent data acquisition from DHT22 - problem with initial loops

Time:10-27

I'm trying to gather the data from DHT22 Humidity and Temperature sensor based on millis() function to avoid the buffer overload and due to how fast the sensor is itself. The point is, that the project has to manage the 72h constant routines, to control the air valve. Because of that 2 actions to be handled, delay is out of range. The problem is, that after setup() and filling in the buffer for average, the loop starts from 12 readings one after another, and eventually after these 12 readings it starts to perform 2 sec. interval readings.


#include <DHT.h>
#include <Adafruit_Sensor.h>
#include <CircularBuffer.h>
#include <time.h>

#define DHTPIN 2
#define DHTTYPE DHT22

using namespace std;

const int sample_rate = 4; // Defining how many samples are gathered to calculate the average 
const int temper_low = -3; // Defining lower range of temperature 
const int temper_high = 20;// Defining high range for temperature
float sum_temper, sum_humid, avg_temp, avg_humid = 0; // variables to calculate the Simple Moving Average
int pre_fill_count = 0; // iterator used for preFill buffer, goes up to 9 and then gets cleared
float test = -255.0;
int mins = 0; //Next 3 vars used for valve control timer
int hours = 0;
int days = 0;
DHT dht(DHTPIN, DHTTYPE); // Defining the dht object
CircularBuffer<float, sample_rate> temper_buffer; // Defining the CircularBuffer for FILO with Moving Average
CircularBuffer<float, sample_rate> humid_buffer; // Same as above
const unsigned long DHT_reads_interval = 2000; //interval used to perform reading action considering the speed of DHT sensor
unsigned long currentMillis = 0; //stores the value of millis() in each iteration of loop()
unsigned long previous_sens_readout = 0; //last time temperature was readed

//State machine for humidity readouts
enum state{
  preFill,
  measure,
  fail
};
state sensorState = preFill;
bool measurmentFlag = false;

//Functions definitions
void calculateAverageTemperature(
  const int& sample_rate,
  float& sum_temper,
  float& sum_humid,
  float& avg_temp,
  float& avg_humid
   );

void getSensorReadings(
    DHT &sensor, 
    CircularBuffer<float, sample_rate> &temper_buffer,
    CircularBuffer<float, sample_rate> &humid_buffer
     );

float readTemperature
(
  state &sensorState,
  DHT &dht
);
float readHumidity
(
  state &sensorState,
  DHT &dht
);

void setup() {
  // Setup, runs once after uC boot

  Serial.begin(9600);
  Serial.println(F("DHTxx test!"));

  dht.begin();
  Serial.println("test value ");
  Serial.println(test);
    // Wait a few seconds between measurements.
  currentMillis = millis();
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)

  ///////////////////////////////////////////////////////////////////////////
  //////////////////////////////INIT BUFFER FILL SECTION////////////////////
  /////////////////////////////////////////////////////////////////////////
  Serial.println("INITIALISING THE BUFFER, PLEASE WAIT... ");
  while(sensorState == preFill && (pre_fill_count <=9)) {
    //PUSHING READINGS TO THE BUFFER
    //DUE TO BUFFER INIT ACTION, IT TAKES C.A. 20 SECS TO MOVE FROM preFill TO measure state!!!
          if(currentMillis - previous_sens_readout >= DHT_reads_interval){
            temper_buffer.push(readTemperature(sensorState, dht));
            Serial.print(pre_fill_count);
            Serial.print(" it Temperature measurement from temper buffer: ");
            Serial.println(temper_buffer[pre_fill_count]);
            humid_buffer.push(readHumidity(sensorState, dht));
            Serial.print(pre_fill_count);
            Serial.print(" it Humidity measurement from temper buffer: ");
            Serial.println(humid_buffer[pre_fill_count]);
            previous_sens_readout = previous_sens_readout   DHT_reads_interval;
            pre_fill_count  ;
          }
        currentMillis = millis();
      }
    sensorState = measure;
    previous_sens_readout = 0;
    currentMillis = millis();
    Serial.print("Program time on the exit of preFill: ");
    Serial.print(int(currentMillis/1000));
    Serial.println(" seconds");
    measurmentFlag = true;
  }

void loop() {

  ///////////////////////////////////////////////////////////////////////////////////
  ////////////////////////////MAIN STATE MACHINE OF PROGRAM/////////////////////////
  /////////////////////////////////////////////////////////////////////////////////
  Serial.println("--------------------HELLO THERE------------------------");
  currentMillis = millis();
  //TOTO - IMPLEMENT ACTUAL USE OF THE calculateAverageTemperature function
  if(sensorState == measure && measurmentFlag == true){
    calculateAverageTemperature(
      sample_rate,
      sum_temper,
      sum_humid,
      avg_temp,
      avg_humid
      );

  if(currentMillis - previous_sens_readout >= DHT_reads_interval){
  getSensorReadings(dht,
   temper_buffer,
    humid_buffer
    );
    previous_sens_readout = previous_sens_readout   DHT_reads_interval;
  }

  if(sensorState == fail){
    Serial.println("FAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP!");
    delay(2000);
    //TODO: RETRY MEASUREMENT AND RAISE LED INDICATOR OF FAIL! 
  }
}
}

void calculateAverageTemperature(
  const int& sample_rate,
  float& sum_temper,
  float& sum_humid,
  float& avg_temp,
  float& avg_humid
   ){
    //iter to gather the sum of 10 values
    for (int k = 0; k < sample_rate; k  ) {
      Serial.println("-----------------HERE I AM!---------------------");
      sum_temper = sum_temper   temper_buffer[k];
      sum_humid = sum_humid   humid_buffer[k];
    }
    //calculate the sum of values
    avg_temp = sum_temper / sample_rate;
    avg_humid = sum_humid / sample_rate;
    sum_temper = sum_humid = 0;
    measurmentFlag = false;
   }

void getSensorReadings(
    DHT &sensor, 
    CircularBuffer<float, sample_rate> &temper_buffer,
    CircularBuffer<float, sample_rate> &humid_buffer
     ){
    //get next measurings
    temper_buffer.push(readTemperature(sensorState, dht));
    humid_buffer.push(readHumidity(sensorState, dht));
    Serial.print(F("Avg Humidity: "));
    Serial.print(avg_humid);
    Serial.print(F("%  Temperature: "));
    Serial.print(avg_temp);
    Serial.print(F("°C \n"));
    measurmentFlag = true;
   }

      //GATHERING TEMPERATURE MEASUREMENT
float readTemperature
(
  state &sensorState,
  DHT &dht
){
  float t = 0;
  bool readed = false;
  for (int r = 0; r < 4; r  ) {
    if ((!readed) && (!isnan(t = dht.readTemperature()))) {
      Serial.print("Temperature readed on iteration: ");
      Serial.println(r);
      readed = true;
      break;
    }
    else if ((r == 3) && (!readed)) {
      Serial.println("Something went wrong with temperature");
      sensorState = fail;
      return -255;
    }
  }
  return t;
}
      //GATHERING HUMIDITY MEASUREMENT
float readHumidity
(
  state &sensorState,
  DHT &dht
){
  float h = 0;
  bool readed = false;
  for (int o = 0; o < 4; o  ) {
    if (!readed && !isnan(h = dht.readHumidity())) {
        Serial.print("Humidity readed on iteration: ");
        Serial.println(o);
        readed = true;
      break;
    }

    else if ((o == 3) && (!readed)) {
      //raise error, blink LED, Kill software
      Serial.println("Something went wrong with Humidity");
      sensorState = fail;
      return -255;
    }
  }
    return h;
}

I've tried many times using some extra flags inside code, nothing seem to really help.

CodePudding user response:

  1. DHT_reads_interval is defined as 2000. It should be expected that

     (currentMillis - previous_sens_readout >= DHT_reads_interval)
    

    is satisfied approximately every 2000 ms, which is 2 seconds.

  2. Regarding the first 12 readings coming one after another, ask yourself what is currentMillis, and what is previous_sens_readout after setup completes?

    In fact, currentMillis retains its value, but previous_sens_readout = 0; is spelled loud and clear. Do you see the consequences?

  • Related