Scope of variables (or something else?)

G'day & Namate to All.

I appreciate the chance to submit a query here on this forum.

Any advice on why the following code always output a zero for the second Serial.println() in each of the two if, else blocks?

I hope that the previously stored value of either A1 or A2 pins is retained at every loop() call as the respective variables are declared out of scope.

const byte inputs[] = {A1, A2};
float milliVolt_A1 = 0;
float milliVolt_A2 = 0;
void setup()
  while (!Serial);
void loop()
    for (int pin = 0; pin < 2 ; pin++){
      int dummy = analogRead(inputs[pin]);  //read values twice as advise
      int value = analogRead(inputs[pin]);
      if (pin == 0){
        float milliVolt_A1 = (value/1023.0)*5*1000;
        Serial.println(milliVolt_A2);                //second println
      else {
        float milliVolt_A2 = (value/1023.0)*5*1000;
        Serial.println(milliVolt_A1);          //second println

Lose the "float"

sp. "Naw, mate"

1 Like

Either remove the float from inside the if block like @anon73444976 says so that the globally declared variables are used or do not declare them global and declare the variable that you wish to retain values static in their functions.

1 Like


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