Can't use variable outside if statement

Hi,

I want to use the variable "prozent" in another void function.
IN following function the variable will be set:

int prozent = 0;
.
.
.
void handleIllumination() {
  if (myWebServer.webserver->hasArg("light-level")) {
    reply = "Illumination level: ";  //String reply
    reply += myWebServer.webserver->arg("light-level").toInt();
    prozent = myWebServer.webserver->arg("light-level").toInt();
    Serial.println(reply);
    Serial.print("prozent: ");
    Serial.println(prozent);
    calcreverse();
    myWebServer.webserver->send(200, "text/plain", reply);
  }

For testing purpose it also prints out at the serial interface.

now the sketch goes on and I wanna use it here:

void calcreverse() {

  //positionvalue = steps / 100;
  prozent = int(100 * positionvalue) / maxdistance;
  positionvalue = maxdistance * prozent / 100;
    Serial.print("Prozent: ");
  Serial.println(prozent);
    Serial.print("maxdistance: ");
  Serial.println(maxdistance);
  Serial.print("Slider positionvalue: ");
  Serial.println(positionvalue);
}

here, the variable "prozent" is just empty.
What I am doing wrong?

The variable prozent must be known in calcreverse() otherwise you'd have got a compiler error.
It is more likely that your subsequent calculation has truncated it to 0.
Print its value before it is manipulated by prozent = int(100 * positionvalue) / maxdistance;

1 Like

Why is it not known? It is global, isn't it? What do i have to do?

You must have misread what I wrote. The variable prozent is known. I said that only because, from your example, it is not completely clear that it is all in the same C++ compilation unit.

What you have to is print the value of prozent as the first statement in calcreverse() then you will see what is changing its value.

1 Like

sorry sorry sorry, I am such an idiot. everything is ok. I messed up the positionvalue (it was 0).
thanks!

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