Go Down

Topic: If and Else if problem (Read 11445 times) previous topic - next topic

aznweirdo

I recently got an Arduino Mega for my school project and ran in tho this problem that my if and else if statement does not work!!! For example i made this program to check that it was the if statement's problem

void loop()
{
     if ( i <= 10)
      {
            Serial.println("A");
       }

      else if ( 10 < i <= 20)
        {
            Serial.println("B");
         }

      else if ( i > 20)
         {
             Serial.println("Reset);
              i = 0 ;
           }

           i++ ;
          delay(500);
}


So the problem i notice on the serial output is that the first if and else if statment is working fine its printing the correct value "A" "B" but once the counter "i" goes above 20 the 3rd if statement never happens and the serial output is just prinitng "B" and counter is incrementing forever.  Is this caused by the defective arduino? or this problem can be solved using software?

Coding Badly

#1
Mar 25, 2010, 07:24 am Last Edit: Mar 25, 2010, 07:24 am by bcook Reason: 1

This...

 else if ( 10 < i <= 20)

Becomes this...

 else if ( (10 < i) <= 20)

Which becomes one of the following...

 else if ( 1 <= 20)
 else if ( 0 <= 20)


As you can see, the condition is always true.  Try this...

 else if ( (10 < i) && (i <= 20) )

aznweirdo

thanks for replying to fast !!! problem solved
THANK YOU SO MUCH !!!!  ;D

Go Up