Broken If/Else (If works, Else doesn't)

Not sure what I'm missing. I have an If/Else that's not working right. The IF statement works fine and stops executing when it should, but the program never enters the Else statement.

void loop() {
    SolidColors();
    FastLED.show();
    delay(1000);

  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
   // print out the value you read:
  Serial.println(sensorValue);
  delay(1);  // delay in between reads for stability    
 

  if(sensorValue >= 50) {
    int s = sensorValue/50;
        for( int b = 56; b >= 56-s; b--){   //Red
          leds[b] = CRGB(0,255,0); 
          FastLED.show();
          delay(10);
          Serial.println("ON");
        }
  }
  else {
      for(int b = 56; b == 36; b--) {
        leds[b] = CRGB::Black;
        FastLED.show();
        Serial.println("Off");
      }
  }

did you print the sensorvalue on serial monitor to make sure its value can vary up and low to 50?

for what I can read here, your code looks right so take a look on the value you use for comparaison.

Perhaps the value of sensorValue always more than 50 and else branch has no chance to run?
What about are values printed in the console? Does it exceeded 50 or not?

@b707 @GrandPete

I just moved the } before my "Off" that now prints, but my LEDs don't change, so it must be in my FOR statement math...

You For is enter only if fisrt IF is true. SO I can assume it is not linked to the fact you don't enter in the second IF.

Did you print values of your sensor on serial monitor and get some values?
Are values < 50 that will be supposed to trigger the second IF?

Yes, sensor value is pretty stable at 0 and it does print "Off" when I would expect. The second statement is an ELSE, so second FOR should run before I'm printing the OFF and Value. IE. LEDs should turn off. But if I move the two print lines inside the FOR statement it they no longer work.

This says...
1). b starts at 56
2). while b == 36 is true continue to loop
3). subtract 1 from b

So... 2)... will not be true on the first time through... so the for loop stops immediately.

Maybe you meant b > 36 ?

@red_car Thanks, I just got that myself. I had it working earlier and hadn't realized I had changed it. It now reads.

for(int b = 36; b <= 56; b++)

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