Disappearing variable

Hi All,

I can not figure out why my const int's from line 24 and 25 disappear after they are put in variable emptyDistance. After reading that a button is pressed I put "emptyValue1"(the empty distance of that tank) into "emptyDistance" (for display later). The Serial.print displays the correct value on line 92 but later when I need that value in line 133 it returns a value of 0.

I can not see why the correct value disappears.

The Serial print values returned are, emptyValue1:

28
emptyDistance 28
graphing 29
emptyDistance 0
start Y 1
adjustedEmpty 99
end

emptyValue2:

35
emptyDistance 35
graphing 13
emptyDistance 0
start Y 1
adjustedEmpty 44
end

Sketch:

// this sketch uses two HC-SR04 ultrasonic boards to report the levels of two tanks
// Tank to be read is determined by reading two switches
// results are displayed on a OLED display using a bargraph and text


#include <Adafruit_SSD1306.h>
#include <Wire.h>

#define OLED_RESET 4   // reset for OLED display

#define trigPin 2    // Set Sensor triger for tank 1  // set Ultrasonic boards trig and echo
#define echoPin 3    // Set Sensor echo for tank 1
#define trigPin2 4   // Set Sensor triger for tank 2
#define echoPin2 5    // Set Sensor echo for tank 2

  const int switchPin1= 10; // set button 1 ,  config as INPUT PULLUP with switch to ground
  const int switchPin2= 11; //sets button 2 same as button 1
  const String whatTank("what Tank");
       int x=1;                   // preset for loop counter, not implemented yet
       int y =(1);           // set graphing to start positionof bar


          int emptyDistance = 0;            //Set empty value for display bar
        const  int emptyValue1 = 28;          // set emptyValue of tank 1 in inches
        const  int emptyValue2 = 35;         // set emptyValue of tank 2 in inches
          int adjustedEmpty;


Adafruit_SSD1306 display(OLED_RESET);

        int buttonState1= HIGH;   // presets buttons
        int buttonState2= HIGH;

  float pingTime;            // time to object and back
  float targetDistance;      //calculated distance


  
void setup() {
  
 Serial.begin (9600);      // put your setup code here, to run once
  
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  
  pinMode(trigPin, OUTPUT);    // setup ports for UltraSensor1
  pinMode(echoPin, INPUT);
  
  pinMode(trigPin2, OUTPUT);   // setup ports for UltraSensor2 
  pinMode(echoPin2, INPUT);

  pinMode(switchPin1, INPUT_PULLUP);   // configure switch inputs with pullup
  pinMode(switchPin2, INPUT_PULLUP);

  digitalWrite(trigPin, LOW);    // make sure trigPin is low
  digitalWrite(trigPin2, LOW);    // make sure trigPin2 is low

    display.clearDisplay();       // clear display
    display.display();            // send clear to display
}


void sendPulse(int triger, int echo){              //  loop to get range data
     
         digitalWrite( triger, LOW);
         delayMicroseconds(5);

         digitalWrite( triger, HIGH);
         delayMicroseconds(1);
         digitalWrite( triger, LOW);
   pingTime = pulseIn( echo, HIGH);   // ping time in microSeconds from echoPin
   targetDistance= (pingTime *0.0135039 /2.0);  // Speed of Sound 0.035039 in/sec
   return;
     }  

void loop() {

     buttonState1= digitalRead(switchPin1);
     buttonState2= digitalRead(switchPin2);
 while (buttonState1== HIGH && buttonState2 == HIGH){

      buttonState1= digitalRead(switchPin1);
      buttonState2= digitalRead(switchPin2);
  display.clearDisplay(); 
  display.display();

 }
     if(buttonState1 == LOW){
         int triger = trigPin;
         int echo = echoPin;
        int emptyDistance = emptyValue1;
     Serial.println(emptyValue1);
     Serial.print("emptyDistance   ");Serial.println(emptyDistance);
         whatTank = ("  Grey 1");
         sendPulse(triger,echo);
     }
     if(buttonState2 ==LOW){
        int triger = trigPin2;
        int echo = echoPin2;
       int emptyDistance = emptyValue2;
     Serial.println(emptyValue2);
     Serial.print("emptyDistance   ");Serial.println(emptyDistance);
         whatTank =("  Grey 2");
        sendPulse(triger, echo);
     }


       for ( int createBar = 17; createBar < 100; createBar ++){          // create bar that returned distance removes
          for ( int y = 17; y <27; y++) {
          display.drawPixel(createBar , y , WHITE);              // draw lines to create Bar from 17 to 26
             }
          }
                                 
     display.setTextSize(2);       // Set Text size for display on OLED
     display.setTextColor(WHITE);  // Set Text color
     display.setCursor(0,0);       // Set text position
     display.print(whatTank);
     display.setCursor(0,15);
     display.print("F");
     display.setCursor(100,15);
     display.print(" E");
     display.setCursor(5,30);
     display.print(targetDistance); display.print(" in");
     display.setCursor(20,50);
     display.setTextSize(2);  
     display.print("From Top");
     display.display();

 int graphing = targetDistance;                          // convert targetDistance to a hole number 


 
                                                   Serial.print("graphing  ");Serial.println(graphing);
                                                   Serial.print("emptyDistance   "); Serial.println(emptyDistance);
                                                             
adjustedEmpty = map(graphing , 0 , 29 , 0 , 99);     //  adjustedEmpty maped to emptyDistance set here to 29 
                                                                                                                                  Serial.print("start Y  "); Serial.println(y); 
                                                   Serial.print("adjustedEmpty  "); Serial.println(adjustedEmpty);                                                         
    for(x =18; x < adjustedEmpty ; x++ ){         // writes black over drawn bar to simulate level 

       for ( int y = 18; y <26; y++) {            // set hight of BLACK bar to erace lines from 10 to 25
           display.drawPixel(x , y , BLACK);     
          }                                                                                             
      display.display();
      }
    
 delay (3000);
 Serial.println("end");
     display.clearDisplay();
     display.display();
 }

WHICH emptyDistance are you concerned about? You have THREE of them defined....

Regards,
Ray L.

When a button is pressed empty distance is loaded with the approach distance for the tank selected with the button press from either empty Value or emptyValue2.

The value is transfered and displayed in the loop that calls for the measurement but later when the measurement needs to be adjusted for the bar graph it returns 0, as shown in the serial print data shown before the code.

The 28, and 35 are the empty distance of each tank.

Can you fix your indenting. The code is hard to follow. Use Tools, Auto Format or ctrl-t.

in this section the emptyDistance gets the correct variable:
if (buttonState1 == LOW) {
int triger = trigPin;
int echo = echoPin;
int emptyDistance = emptyValue1;
Serial.println(emptyValue1);
Serial.print("emptyDistance "); Serial.println(emptyDistance);
whatTank = (" Grey 1");
sendPulse(triger, echo);
}
if (buttonState2 == LOW) {
int triger = trigPin2;
int echo = echoPin2;
int emptyDistance = emptyValue2;
Serial.println(emptyValue2);
Serial.print("emptyDistance "); Serial.println(emptyDistance);
whatTank = (" Grey 2");
sendPulse(triger, echo);
}

But later when I need to use the emptyDistance in the map function it has a value of ZERO. The code here has 29 in the place thatI need emptyDistance:
int graphing = targetDistance; // convert targetDistance to a hole number

Serial.print("graphing "); Serial.println(graphing);
Serial.print("emptyDistance "); Serial.println(emptyDistance);

adjustedEmpty = map(graphing , 0 , 29 , 0 , 99); // adjustedEmpty maped to emptyDistance set here to 29
Serial.print("start Y "); Serial.println(y);
Serial.print("adjustedEmpty "); Serial.println(adjustedEmpty);

Here is the code reFormated

// this sketch uses two HC-SR04 ultrasonic boards to report the levels of two tanks
// Tank to be read is determined by reading two switches
// results are displayed on a OLED display using a bargraph and text


#include <Adafruit_SSD1306.h>
#include <Wire.h>

#define OLED_RESET 4   // reset for OLED display

#define trigPin 2    // Set Sensor triger for tank 1  // set Ultrasonic boards trig and echo
#define echoPin 3    // Set Sensor echo for tank 1
#define trigPin2 4   // Set Sensor triger for tank 2
#define echoPin2 5    // Set Sensor echo for tank 2

const int switchPin1 = 10; // set button 1 ,  config as INPUT PULLUP with switch to ground
const int switchPin2 = 11; //sets button 2 same as button 1
const String whatTank("what Tank");
int x = 1;                 // preset for loop counter, not implemented yet
int y = (1);          // set graphing to start positionof bar


int emptyDistance = 0;            //Set empty value for display bar
const  int emptyValue1 = 28;          // set emptyValue of tank 1 in inches
const  int emptyValue2 = 35;         // set emptyValue of tank 2 in inches
int adjustedEmpty;


Adafruit_SSD1306 display(OLED_RESET);

int buttonState1 = HIGH;  // presets buttons
int buttonState2 = HIGH;

float pingTime;            // time to object and back
float targetDistance;      //calculated distance



void setup() {

  Serial.begin (9600);      // put your setup code here, to run once

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  pinMode(trigPin, OUTPUT);    // setup ports for UltraSensor1
  pinMode(echoPin, INPUT);

  pinMode(trigPin2, OUTPUT);   // setup ports for UltraSensor2
  pinMode(echoPin2, INPUT);

  pinMode(switchPin1, INPUT_PULLUP);   // configure switch inputs with pullup
  pinMode(switchPin2, INPUT_PULLUP);

  digitalWrite(trigPin, LOW);    // make sure trigPin is low
  digitalWrite(trigPin2, LOW);    // make sure trigPin2 is low

  display.clearDisplay();       // clear display
  display.display();            // send clear to display
}


void sendPulse(int triger, int echo) {             //  loop to get range data

  digitalWrite( triger, LOW);
  delayMicroseconds(5);

  digitalWrite( triger, HIGH);
  delayMicroseconds(1);
  digitalWrite( triger, LOW);
  pingTime = pulseIn( echo, HIGH);   // ping time in microSeconds from echoPin
  targetDistance = (pingTime * 0.0135039 / 2.0); // Speed of Sound 0.035039 in/sec
  return;
}

void loop() {

  buttonState1 = digitalRead(switchPin1);
  buttonState2 = digitalRead(switchPin2);
  while (buttonState1 == HIGH && buttonState2 == HIGH) {

    buttonState1 = digitalRead(switchPin1);
    buttonState2 = digitalRead(switchPin2);
    display.clearDisplay();
    display.display();

  }
  if (buttonState1 == LOW) {
    int triger = trigPin;
    int echo = echoPin;
    int emptyDistance = emptyValue1;
    Serial.println(emptyValue1);
    Serial.print("emptyDistance   "); Serial.println(emptyDistance);
    whatTank = ("  Grey 1");
    sendPulse(triger, echo);
  }
  if (buttonState2 == LOW) {
    int triger = trigPin2;
    int echo = echoPin2;
    int emptyDistance = emptyValue2;
    Serial.println(emptyValue2);
    Serial.print("emptyDistance   "); Serial.println(emptyDistance);
    whatTank = ("  Grey 2");
    sendPulse(triger, echo);
  }


  for ( int createBar = 17; createBar < 100; createBar ++) {         // create bar that returned distance removes
    for ( int y = 17; y < 27; y++) {
      display.drawPixel(createBar , y , WHITE);              // draw lines to create Bar from 17 to 26
    }
  }

  display.setTextSize(2);       // Set Text size for display on OLED
  display.setTextColor(WHITE);  // Set Text color
  display.setCursor(0, 0);      // Set text position
  display.print(whatTank);
  display.setCursor(0, 15);
  display.print("F");
  display.setCursor(100, 15);
  display.print(" E");
  display.setCursor(5, 30);
  display.print(targetDistance); display.print(" in");
  display.setCursor(20, 50);
  display.setTextSize(2);
  display.print("From Top");
  display.display();

  int graphing = targetDistance;                          // convert targetDistance to a hole number



  Serial.print("graphing  "); Serial.println(graphing);
  Serial.print("emptyDistance   "); Serial.println(emptyDistance);

  adjustedEmpty = map(graphing , 0 , 29 , 0 , 99);     //  adjustedEmpty maped to emptyDistance set here to 29
  Serial.print("start Y  "); Serial.println(y);
  Serial.print("adjustedEmpty  "); Serial.println(adjustedEmpty);
  for (x = 18; x < adjustedEmpty ; x++ ) {      // writes black over drawn bar to simulate level

    for ( int y = 18; y < 26; y++) {           // set hight of BLACK bar to erace lines from 10 to 25
      display.drawPixel(x , y , BLACK);
    }
    display.display();
  }

  delay (3000);
  Serial.println("end");
  display.clearDisplay();
  display.display();
}

But later when I need to use the emptyDistance in the map function it has a value of ZERO.

There are global and local variables named emptyDistance.

Th global variable is what is used in the map function . It was initialized to 0, and has never received any other values.

The local copies of emptyDistance in the buttonState conditionals do not carry through to the map function.

I'm not sure what you are tying to achieve, but perhaps you should start by not redeclaring the local copies in both conditionals.

 //int emptyDistance = emptyValue1//;
  emptyDistance = emptyValue1;

// int emptyDistance = emptyValue2;
emptyDistance = emptyValue2

Teling2:

in this section the emptyDistance gets the correct variable:

if (buttonState1 == LOW) {
   int triger = trigPin;
   int echo = echoPin;
   int emptyDistance = emptyValue1;
   Serial.println(emptyValue1);
   Serial.print("emptyDistance   "); Serial.println(emptyDistance);
   whatTank = ("  Grey 1");
   sendPulse(triger, echo);
 }
 if (buttonState2 == LOW) {
   int triger = trigPin2;
   int echo = echoPin2;
   int emptyDistance = emptyValue2;
   Serial.println(emptyValue2);
   Serial.print("emptyDistance   "); Serial.println(emptyDistance);
   whatTank = ("  Grey 2");
   sendPulse(triger, echo);
 }

Near the top of your program, you create a global vaurable names emptyDistance, and set its value equal to 0;

int emptyDistance = 0;            //Set empty value for display bar

Later on, in this section, you create a NEW local variable also named emptyDistance, and set its value equal to the value of emptyValue1. You then print the value of that new variable. But, at the closing '}' of the "if", this new variable goes out of scope and is discarded. You also create two new variables, triger and echo, which are both discarded before ever being used for anything at all.

  if (buttonState1 == LOW) {
    int triger = trigPin;
    int echo = echoPin;
    int emptyDistance = emptyValue1;
    Serial.println(emptyValue1);
    Serial.print("emptyDistance   "); Serial.println(emptyDistance);
    whatTank = ("  Grey 1");
    sendPulse(triger, echo);
  }

Then in this section, you create yet another NEW variable named emptyDistance, and set its value equal to the value of emptyValue2. You then print the value of that new variable. But, at the closing '}', that new variable also goes out of scope and is discarded. You also create two more new variables, triger and echo, which are also discarded before ever being used for anything at all.

  if (buttonState2 == LOW) {
    int triger = trigPin2;
    int echo = echoPin2;
    int emptyDistance = emptyValue2;
    Serial.println(emptyValue2);
    Serial.print("emptyDistance   "); Serial.println(emptyDistance);
    whatTank = ("  Grey 2");
    sendPulse(triger, echo);
  }

So you NEVER change the value of the global variable emptyDistance (or triger, or echo...). You need to do some reading on variable scope, and get a good understanding the difference between global and local variables, and the difference between declaring a variable, and actually using (i.e. - reading and writing) a variable.

Regards,
Ray L.

Ok, I removed the "int" from the code in the buttonState section and it compiled and ran correctly.
I swear I tried that and it would not compile.

Can you tell me why i need the "int" before the " triger" and "echo" variables ?

if I remove it I get this:

OLED_Display_alt_bargraph_v1:97: error: 'triger' was not declared in this scope

triger = trigPin2;

exit status 1
'triger' was not declared in this scope

I thought that I defined these in the begining.

Teling2:
Can you tell me why i need the "int" before the " triger" and "echo" variables ?

Same answer: Because variable scope matters! WHERE to declare a variable matters. If you don't get a good understanding of variable scope, you're going to spend a whole lotta time beating your head against the wall....

Regards,
Ray L.

Thank you, I will read up on vatiable scope.