First project, quick question. If statement not executed when condition met

Hello everyone,
I’m working on my first project and i need some help to understand a behavior of a part of my program.

Don’t pay attention to all the comment, i took part of programs from example everywhere and didn’t clean it yet.
My question is regarding the last part of my program.
i have an if statement and a else statement. The action in the if statement are not executed when the condition are met but the action in the else statement are executed when the if statement condition are not met. Here is the part of the program i’m talking about:

if (levelswitchstate == HIGH)
      {
        Serial.println("turn relay on");
      }
      else
      {
        Serial.println("turn relay off");
          
      }

Here is the whole program :

#include <OneWire.h> // Library pour les sensor temperature OneWire (tous sur le meme input)
#include <DallasTemperature.h> //Librairy pour sensor temperature
#include <Event.h> //Librairy pour évenement callback(caller une fonction)
#include <Timer.h> //Librairy pour setter des timers

Timer timer1;

/*-----( Declare Constants and Pin Numbers )-----*/
#define ONE_WIRE_BUS_PIN 2

/*-----( Declare objects )-----*/
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS_PIN);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

/*-----( Declare Variables )-----*/
// Assign the addresses of your 1-Wire temp sensors.
// See the tutorial on how to obtain these addresses:
// http://www.hacktronics.com/Tutorials/arduino-1-wire-address-finder.html

DeviceAddress poolprobe = { 0x28, 0x8B, 0x3B, 0x26, 0x06, 0x00, 0x00, 0x50 }; 
DeviceAddress heaterprobe = { 0x28, 0xCD, 0x20, 0x2B, 0x06, 0x00, 0x00, 0x06 };
//DeviceAddress Probe03 = { 0x28, 0x4D, 0x8D, 0x40, 0x04, 0x00, 0x00, 0x78 };
//DeviceAddress Probe04 = { 0x28, 0x9A, 0x80, 0x40, 0x04, 0x00, 0x00, 0xD5 };
//DeviceAddress Probe05 = { 0x28, 0xE1, 0xC7, 0x40, 0x04, 0x00, 0x00, 0x0D };
const int levelswitch = 11;
int lastlevelswitchstate = LOW;
const int heatervalve = 10;
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 500;    // the debounce time; increase if the output flickers


void setup()   /****** SETUP: RUNS ONCE ******/
{
  // start serial port to show results
  Serial.begin(115200);
  Serial.print("Initializing Temperature Control Library Version ");
  Serial.println(DALLASTEMPLIBVERSION);
  
  // Initialize the Temperature measurement library
  sensors.begin();
  
  // set the resolution to 10 bit (Can be 9 to 12 bits .. lower is faster)
  sensors.setResolution(poolprobe, 10);
  sensors.setResolution(heaterprobe, 10);
  //sensors.setResolution(Probe03, 10);
 // sensors.setResolution(Probe04, 10);
//  sensors.setResolution(Probe05, 10);



timer1.every(1000, gettemp); // définir frequence de la fonction
timer1.every(5000, openvalve); // définir frequence de la fonction
timer1.every(1000, waterlevel);// check water level and change status of fillingvalve
}//--(end setup )---

void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
 timer1.update();
 
}  
void gettemp()
{
Serial.println();
  Serial.print("Number of Devices found on bus = ");  
  Serial.println(sensors.getDeviceCount());   
  Serial.print("Getting temperatures... ");  
  Serial.println();   
  
  // Command all devices on bus to read temperature  
  sensors.requestTemperatures();  
  
  Serial.print("Pool temperature is:   ");
  printTemperature(poolprobe);
  Serial.println();

  Serial.print("Heater temperature is:   ");
  printTemperature(heaterprobe);
  Serial.println();
 
  //Serial.print("Probe 03 temperature is:   ");
  //printTemperature(Probe03);
 // Serial.println();
   
 // Serial.print("Probe 04 temperature is:   ");
 // printTemperature(Probe04);
 // Serial.println();
  
 // Serial.print("Probe 05 temperature is:   ");
 // printTemperature(Probe05);
 // Serial.println();
   
  
}//--(end main loop )---

/*-----( Declare User-written Functions )-----*/
void printTemperature(DeviceAddress deviceAddress)
{

float tempC = sensors.getTempC(deviceAddress);

   if (tempC == -127.00) 
   {
   Serial.print("Error getting temperature  ");
   } 
   else
   {
   Serial.print("C: ");
   Serial.print(tempC);
   Serial.print(" F: ");
   Serial.print(DallasTemperature::toFahrenheit(tempC));
   }

}// End printTemperature
//*********( THE END )***********


void openvalve()
{
 
  pinMode (heatervalve, OUTPUT);
    
    
float pooltemp = sensors.getTempC(poolprobe);
float heatertemp = sensors.getTempC(heaterprobe);
  
if (pooltemp<heatertemp){
digitalWrite(heatervalve,HIGH);

Serial.println("on");

  }
  else{
    digitalWrite(heatervalve,LOW);
    Serial.println("off");
    Serial.println(pooltemp);
    Serial.println(heatertemp);
 } 
 } 
 void waterlevel()
{ 
  Serial.println("test");
  
   pinMode (levelswitch, INPUT);
   // read the state of the switch into a local variable:
   int levelswitchstate = digitalRead(levelswitch);
   Serial.println (levelswitchstate);



   
   //if state changed
   if (levelswitchstate != lastlevelswitchstate)
   {
    // reset the debouncing timer
    lastDebounceTime = millis();
   }
   if ((millis() - lastDebounceTime) > debounceDelay)
    {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the levelswitch state has changed:
    if (levelswitchstate != lastlevelswitchstate) 
    {
      lastlevelswitchstate = levelswitchstate;
    }
      // 
      if (levelswitchstate == HIGH)
      {
        Serial.println("turn relay on"); // This part isn't executed when condition if is met
      }
      else
      {
        Serial.println("turn relay off"); //this one is executed when the if condition isn't met
          
      }
      
    }
}



//float tempC = sensors.getTempC(deviceAddress);

I guess it’s a pretty simple error but i can’t figured it out.

Best regards

Yes, pretty simple error that everyone makes in the beginning.

your "levelswitchstate is only defined in and for the function "void waterlevel()", so it is only available in that function. Move it''s define to the top of your program where the other variable are defined.

Paul

Hi Paul,
Thank you for your answer.

I tried to switch it in the top section but it didn't work.
In fact, if i assign it in the top section, the function does not work at all and the state isn't updated.(always show 0 in the serial monitor)

Also, the if statement is in the void waterlevel() section so it should not be a problem if i only assign the variable it in this section.

Can I suggest that you run the IDE’s auto format tool before posting your code, and check your wiring?

Try printing the value of levelswitchstate just before you test it. Is the value what you expect ?

Gariep:
I tried to switch it in the top section but it didn't work.

You need to post the revised program - maybe you did not do it properly.

And please post the program in a new Reply so we can compare it to the earlier code if necessary.

...R

Moved pinMode to setup, removed lots of comments and added some debug printing. Let us know what yoy get in serial monitor.

#include <OneWire.h> // Library pour les sensor temperature OneWire (tous sur le meme input)
#include <DallasTemperature.h> //Librairy pour sensor temperature
#include <Event.h> //Librairy pour évenement callback(caller une fonction)
#include <Timer.h> //Librairy pour setter des timers

Timer timer1;

/*-----( Declare Constants and Pin Numbers )-----*/
#define ONE_WIRE_BUS_PIN 2

/*-----( Declare objects )-----*/
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS_PIN);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

DeviceAddress poolprobe = { 0x28, 0x8B, 0x3B, 0x26, 0x06, 0x00, 0x00, 0x50 };
DeviceAddress heaterprobe = { 0x28, 0xCD, 0x20, 0x2B, 0x06, 0x00, 0x00, 0x06 };
const byte levelswitch = 11;
bool lastlevelswitchstate = LOW;
bool levelswitchstate = LOW;
const byte heatervalve = 10;
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 500;    // the debounce time; increase if the output flickers


void setup()
{
  Serial.begin(115200);
  Serial.print("Initializing Temperature Control Library Version ");
  Serial.println(DALLASTEMPLIBVERSION);

  // Initialize the Temperature measurement library
  sensors.begin();
  pinMode (heatervalve, OUTPUT);
  pinMode (levelswitch, INPUT);

  // set the resolution to 10 bit (Can be 9 to 12 bits .. lower is faster)
  sensors.setResolution(poolprobe, 10);
  sensors.setResolution(heaterprobe, 10);

  timer1.every(1000, gettemp); // définir frequence de la fonction
  timer1.every(5000, openvalve); // définir frequence de la fonction
  timer1.every(1000, waterlevel);// check water level and change status of fillingvalve
}

void loop()
{
  timer1.update();
}

void gettemp()
{
  Serial.println();
  Serial.print("Number of Devices found on bus = ");
  Serial.println(sensors.getDeviceCount());
  Serial.print("Getting temperatures... ");
  Serial.println();

  sensors.requestTemperatures();

  Serial.print("Pool temperature is:   ");
  printTemperature(poolprobe);
  Serial.println();

  Serial.print("Heater temperature is:   ");
  printTemperature(heaterprobe);
  Serial.println();

}

/*-----( Declare User-written Functions )-----*/
void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC == -127.00)
  {
    Serial.print("Error getting temperature  ");
  }
  else
  {
    Serial.print("C: ");
    Serial.print(tempC);
    Serial.print(" F: ");
    Serial.print(DallasTemperature::toFahrenheit(tempC));
  }

}// End printTemperature

void openvalve()
{
  float pooltemp = sensors.getTempC(poolprobe);
  float heatertemp = sensors.getTempC(heaterprobe);
  if (pooltemp < heatertemp) {
    digitalWrite(heatervalve, HIGH);
    Serial.println("on");
  }
  else
  {
    digitalWrite(heatervalve, LOW);
    Serial.println("off");
    Serial.println(pooltemp);
    Serial.println(heatertemp);
  }
}

void waterlevel()
{
  Serial.println("waterlevel reading");
  int levelswitchstate = digitalRead(levelswitch);
  Serial.println (levelswitchstate);
  if (levelswitchstate != lastlevelswitchstate)
  {
    Serial.println("lastDebounceTime updated");
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay)
  {
    Serial.println("debounceDelay exceeded, levelswitchstate is");
    Serial.println (levelswitchstate);
    // if (levelswitchstate != lastlevelswitchstate) // This does nothing useful.
    // {
    lastlevelswitchstate = levelswitchstate;
    // }
    if (levelswitchstate == HIGH)
    {
      Serial.println("turn relay on"); // This part isn't executed when condition if is met
    }
    else
    {
      Serial.println("turn relay off"); //this one is executed when the if condition isn't met
    }
  }
}
lastlevelswitchstate = levelswitchstate;

You need to make this assignment outside of the debounce conditional. You are constantly resetting the value of lastDebounceTime millis() and never time out.

void waterlevel()
{
  Serial.println("waterlevel reading");
  int levelswitchstate = digitalRead(levelswitch);
  Serial.println (levelswitchstate);
  if (levelswitchstate != lastlevelswitchstate)
  {
    Serial.println("lastDebounceTime updated");
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay)
  {
    Serial.println("debounceDelay exceeded, levelswitchstate is");
    Serial.println (levelswitchstate);
    // if (levelswitchstate != lastlevelswitchstate) // This does nothing useful.
    // {
   // lastlevelswitchstate = levelswitchstate;
    // }
    if (levelswitchstate == HIGH)
    {
      Serial.println("turn relay on"); // This part isn't executed when condition if is met
    }
    else
    {
      Serial.println("turn relay off"); //this one is executed when the if condition isn't met
    }
  }
  lastlevelswitchstate = levelswitchstate;
}

Thank you all for your help,

@cattledog you were right. it’s now working thanks!