Says "lv" and "hv" are not declared in this scope

I am working on an intelligent plant watering system. It should water the plants when the moisture value gets too low. It says "lv" and "hv" are not declared in this scope. Here are 2 screenshots:


Please don't post pictures of code.

Your problem is you declared variables local to the code blocks for the if and else statements.

Declare hv and lv as global and then just assign values to them in the if/else statement

It still gives me the same errors.

const int pumpPin = 12;
void setup() {
  const int lv = 246; //change this to 123 if you are watering plants that are not vegetables
  const int hv = 491; //change this to 246 if you are watering plants that are not vegetables
}

void loop() {
  int m = analogRead(0);
  if (m <= lv){
    digitalWrite(pumpPin,HIGH);
  }
  if (m >= hv){
    digitalWrite(pumpPin, LOW);
  }
}

The variables lv and hv were declared as local variables.
To be used in various functions they need to be declared as global.

1 Like

Follow @ruilviana suggestion and
Change it to this:

const int pumpPin = 12; // declare pump pin
const int lv = 246; //change this to 123 if you are watering plants that are not vegetables
const int hv = 491; //change this to 246 if you are watering plants that are not vegetables
void setup() {
 // no more code needed here for now
}

void loop() {
  int m = analogRead(0); // get analog input value
  if (m <= lv){ // check if analog input is lower  then low value
    digitalWrite(pumpPin,HIGH); // turn pump on
  }
  if (m >= hv){ // check if analog input is higher then high value
    digitalWrite(pumpPin, LOW);// turn pump off
  }
}
const int pumpPin = 12;
  const int lv = 246; //change this to 123 if you are watering plants that are not vegetables
  const int hv = 491; //change this to 246 if you are watering plants that are not vegetables


void setup() {
}

void loop() {
  int m = analogRead(0);
  if (m <= lv){
    digitalWrite(pumpPin,HIGH);
  }
  if (m >= hv){
    digitalWrite(pumpPin, LOW);
  }
}

Try this. The change is small but it makes GLOBAL variables.

void setup() is a function. Variables declared inside of functions or inner loops STAY inside of them. If the variables are declared static, they keep their values otherwise they're gone when the function returns or the inner loop ends. Temporary variables are put on the stack and static variables go on the heap. On AVR's, conserve your RAM to not using an int where a byte (unsigned) or a char (signed) will do. Pin numbers should be bytes forinstance.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.