Pages: [1]   Go Down
Author Topic: If and Else if problem  (Read 9611 times)
0 Members and 2 Guests are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 2
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
Logged

Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 206
Posts: 12894
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


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) )
« Last Edit: March 25, 2010, 01:24:24 am by bcook » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 2
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: