Need help in making a small code for counting

I'm working with a DHT (Humidity and Temperature) Sensor.
Here is the plain code required for the arduino to read from the DHT sensor and print the value on the Serial monitor:

#include "dht.h"
#define dht_apin A0 // Analog Pin sensor is connected to
 
dht DHT;
void setup(){
 
  Serial.begin(9600);
  delay(500); //Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000); //Wait before accessing Sensor
 
}//end "setup()"
 
void loop(){
  //Start of Program 
    DHT.read11(dht_apin);
    
    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature); 
    Serial.print("°C  ");
    delay(2000);
    
}// end loop()

I want to introduce a variable, say x. I want the value of x to increase (from 0 to 1), as the value of DHT.humidity exceeds a desired value (let it be 45). After, DHT.humidity will become less than the desired value. When the component exceeds the desired value again, the x should get added with 1 (i.e x becomes 2). And so on upto a limit (for x). Assume the limit to be <6. If the counting variable (x) exceeds the limit, it's value should become 0 (i.e the counting gets restarted). The value should get printed on Serial Monitor as x = (value of x).

Raj_Srikar:
I want to introduce a variable, say x. I want the value of x to increase (from 0 to 1), as the value of DHT.humidity exceeds a desired value (let it be 45)

That sounds straightforward - what have you tried? It is much easier to help if you post the code that represents your best attempt and tell us exactly what it does and what you want it to do that is different.

By the way don't use single character names for variables - it makes debugging very difficult because you can't easily serach and find all the instances of the variable.

...R

There was some problems with your "basic" code I took the liberty of fixing.

#include <DHT.h>

//defines
#define dht_apin A0 // Analog Pin sensor is connected to
#define MAX_X               6       //# number of reading transitions over thresh before resetting
#define HUMID_HIGH_THRESH   45      //% Rh threshold to bump X
#define UPDATE_TIME         2000UL  //mS between readings and print updates

DHT
    dht( dht_apin, DHT11 );

unsigned int
    x;
float
    fTemperature,
    fHumidity,
    fLastHumidity;

void setup()
{ 
    Serial.begin(9600);
    delay(500); //Delay to let system boot
    Serial.println("DHT11 Humidity & temperature Sensor\n\n");
    delay(1000); //Wait before accessing Sensor
    
    dht.begin();    
    fHumidity = dht.readHumidity();
    fLastHumidity = fHumidity;
    fTemperature = dht.readTemperature();
    x = 0;
    
}//setup
 
void loop()
{
    unsigned long
        timeNow;
    static unsigned long
        timeUpdate = 0;

    timeNow = millis();
    if( (timeNow - timeUpdate) >= UPDATE_TIME )
    {
        timeUpdate = timeNow;
        
        fHumidity = dht.readHumidity();
        fTemperature = dht.readTemperature();

        //if humidity in excess of high threshold?
        if( fHumidity > HUMID_HIGH_THRESH )
        {
            //yes; is this a cross of that threshold?            
            if( fLastHumidity <= HUMID_HIGH_THRESH )
            {
                //yes; bump x but limit it to MAX_X                
                x++;
                if( x >= MAX_X )
                    x = 0;
            
            }//if
                
        }//if
        
        //save the last reading so we know if we crossed
        //the threshold            
        fLastHumidity = fHumidity;

               
        Serial.print( "Current humidity = " ); Serial.print( fHumidity, 0 ); Serial.println( "%  ");
        Serial.print( "X = " ); Serial.println( x );
        Serial.print( "Temperature = "); Serial.print( fTemperature, 1 ); Serial.println( "°C  ");
        
    }//if
    
}//loop

Blackfin:
There was some problems with your "basic" code I took the liberty of fixing.

My code is all good and working perfectly. I really don't understand why you have to fix it and also you've changed / updated the time. The code has become more complicated now. I just wanted to add a counting variable (as per the explanation above). I tried using your code. But I got an error: "Error compiling for board Arduino/Genuino Uno". And thank you so much for your effort. Please try making it simplified.

Robin2:
That sounds straightforward - what have you tried? It is much easier to help if you post the code that represents your best attempt and tell us exactly what it does and what you want it to do that is different.

My best attempt to this, as a newbie is this:

#include "dht.h"
#define dht_apin A0 // Analog Pin sensor is connected to
 
dht DHT;
void setup(){
 
  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000);//Wait before accessing Sensor
 
}//end "setup()"
 
void loop(){
  //Start of Program 
    DHT.read11(dht_apin);
    
    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature); 
    Serial.print("°C  ");
    int x = 0;
    int value = DHT.humidity;
    if (value > 45) 
    {
      x ++;
    }
    Serial.println(x); 
    delay(2000);
    
}// end loop()

The result of this code is, as soon as the value of humidity drops below 45, the value of the counting variable (x) returns back to 0.

as soon as the value of humidity drops below 45, the value of the counting variable (x) returns back to 0.

That is because you are declaring the variable again each time each time through loop()
   int x = 0;which resets its value

Either declare the variable static
   static int x = 0;or make it a global variable and declare it before setup()

Raj_Srikar:
My code is all good and working perfectly. I really don't understand why you have to fix it and also you've changed / updated the time. The code has become more complicated now. I just wanted to add a counting variable (as per the explanation above). I tried using your code. But I got an error: "Error compiling for board Arduino/Genuino Uno". And thank you so much for your effort. Please try making it simplified.
My best attempt to this, as a newbie is this:

When I compiled your code the first time I got:

Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

sketch_jan20f:1:17: error: dht.h: No such file or directory

compilation terminated.

exit status 1
dht.h: No such file or directory

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Okay. No biggie. Maybe you really do have a file called "dht.h" in your project folder. I had to change it to <DHT.h>. After I did that:

Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

sketch_jan20f:4:1: error: 'dht' does not name a type

 dht DHT;

 ^

C:\Use...\sketch_jan20f.ino: In function 'void loop()':

sketch_jan20f:16:8: error: expected unqualified-id before '.' token

     DHT.read11(dht_apin);

        ^

sketch_jan20f:19:21: error: expected primary-expression before '.' token

     Serial.print(DHT.humidity);

                     ^

sketch_jan20f:22:21: error: expected primary-expression before '.' token

     Serial.print(DHT.temperature); 

                     ^

exit status 1
'dht' does not name a type

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I realized you have dht DHT backwards, so I corrected it to DHT dht; Then:

Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

sketch_jan20f:4:5: error: no matching function for call to 'DHT::DHT()'

 DHT dht;

     ^

In file included from C:\User...\sketch_jan20f.ino:1:0:

C:\User...\Arduino\libraries\DHT_sensor_library/DHT.h:41:4: note: candidate: DHT::DHT(uint8_t, uint8_t, uint8_t)

    DHT(uint8_t pin, uint8_t type, uint8_t count=6);

    ^

C:\User...\Arduino\libraries\DHT_sensor_library/DHT.h:41:4: note:   candidate expects 3 arguments, 0 provided

C:\User...\Arduino\libraries\DHT_sensor_library/DHT.h:39:7: note: candidate: constexpr DHT::DHT(const DHT&)

 class DHT {

       ^

C:\User...\Arduino\libraries\DHT_sensor_library/DHT.h:39:7: note:   candidate expects 1 argument, 0 provided

C:\User...\Arduino\libraries\DHT_sensor_library/DHT.h:39:7: note: candidate: constexpr DHT::DHT(DHT&&)

C:\User...\Arduino\libraries\DHT_sensor_library/DHT.h:39:7: note:   candidate expects 1 argument, 0 provided

C:\User...\Arduino\sketch_jan20f\sketch_jan20f.ino: In function 'void loop()':

sketch_jan20f:16:8: error: expected unqualified-id before '.' token

     DHT.read11(dht_apin);

        ^

sketch_jan20f:19:21: error: expected primary-expression before '.' token

     Serial.print(DHT.humidity);

                     ^

sketch_jan20f:22:21: error: expected primary-expression before '.' token

     Serial.print(DHT.temperature); 

                     ^

exit status 1
no matching function for call to 'DHT::DHT()'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Then I saw that you were using this to read humidity (and temperature):

dht.humidity

when the library proper usage is more like:

fHumidity = dht.readHumidity();

I dunno. Maybe you've got a special or downlevel library but your code didn't work out of the box on my machine. The fact that it doesn't compile on yours suggests you do have different libraries or maybe you've somehow been changing your libs...

If the code didn't compile on your machine how do you know that the update time is no longer the same ("...and also you've changed / updated the time...")? Is it because you don't see the dreaded "delay(2000)" at the end of loop()??

Good luck.

UKHeliBob:
That is because you are declaring the variable again each time each time through loop()
  int x = 0;which resets its value

I tried declaring the variable x before the setup(). Here's how the code looks like:

#include "dht.h"
#define dht_apin A0 // Analog Pin sensor is connected to
   int x = 0;
dht DHT;
void setup(){
 
  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000);//Wait before accessing Sensor
 
}//end "setup()"
 
void loop(){
  //Start of Program 
    DHT.read11(dht_apin);
    
    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature); 
    Serial.print("°C  ");
    int value = DHT.humidity;
    if (value > 45) 
    {x++;}
    Serial.println(x); 
    delay(2000);
    
}// end loop()

It has stopped returning back to 0 when below 45. Also it does increases the value of x. But when the value of humidity is more than 45 the x keeps on increasing it's value per line. And as soon as the humidity drops below 45, the x stops increasing. Now, I think I'm pretty close to it. I just want to stop the x to increase it's value as the humidity is above 45. Can you make it possible?

Blackfin:
I dunno. Maybe you've got a special or downlevel library but your code didn't work out of the box on my machine. The fact that it doesn't compile on yours suggests you do have different libraries or maybe you've somehow been changing your libs...

Yeah! You're right. I got a very basic Library. Also code is so simplified, so that it can be understood by beginners.

Blackfin:
Is it because you don't see the dreaded "delay(2000)" at the end of loop()??

And yes. I saw that. But I don't feel it necessary to convert the time to millis. What you've done is perfect. But I think this just making it more complicated.

Can you make it possible?

I could, but it would be better if you did it.

You need to detect when the humidity becomes more than 45 rather than when it is above 45

Have a look at the StateChangeDetection example in the IDE

Also it does increases the value of x. But when the value of humidity is more than 45 the x keeps on increasing it's value per line. And as soon as the humidity drops below 45, the x stops increasing. Now, I think I'm pretty close to it. I just want to stop the x to increase it's value as the humidity is above 45.

That's the real pain of it indeed, and is the whole reason for the "complicated" code that Blackfin posted. Believe me, I know it does seem unnecessarily complicated, but it's the only way I've found to do what I'm thinking you want to do.

I highly suggest you try his code again. Also, make sure you have the correct board/processor/port selected under tools and if you get the same error again try copying the whole error code as it might have more clues. The problem is most likely a difference in the dht libraries you have and he doesn't know what yours is asking for.

At the very least, read through it carefully and try and understand why he would do it that way (hint: it's to fix the exact problem you're experiencing now).

If you find another way to do it, please post the code here as I don't like it either and would love an easier way!

Blackfin:
I dunno. Maybe you've got a special or downlevel library but your code didn't work out of the box on my machine. The fact that it doesn't compile on yours suggests you do have different libraries or maybe you've somehow been changing your libs...

KitNo:
That's the real pain of it indeed, and is the whole reason for the "complicated" code that Blackfin posted. Believe me, I know it does seem unnecessarily complicated, but it's the only way I've found to do what I'm thinking you want to do.

I highly suggest you try his code again. Also, make sure you have the correct board/processor/port selected under tools and if you get the same error again try copying the whole error code as it might have more clues. The problem is most likely a difference in the dht libraries you have and he doesn't know what yours is asking for.

At the very least, read through it carefully and try and understand why he would do it that way (hint: it's to fix the exact problem you're experiencing now).

You both are right! Blackfin's code is perfect. The thing is I'm just facing a problem while compiling it. So, I have uninstalled my old DHT library and installed a new one, as he said. And yes, finally it worked! Thank you very much for your effort!

KitNo:
If you find another way to do it, please post the code here as I don't like it either and would love an easier way!

Yes!! I'll keep trying to find another simple way to do it. As soon as I get it, I'll post it immediately. :wink:

UKHeliBob:
I could, but it would be better if you did it.

You need to detect when the humidity becomes more than 45 rather than when it is above 45

Have a look at the StateChangeDetection example in the IDE

It's very helpful! I had a look at the state change detection example. Now I'll try my best to render it into my old DHT sketch to make it simple (if possible).

You guys are awsome! Thank you all for the help!! :grinning: