Problem breaking a for loop

Hi guys,

Not sure what I’m doing wrong. I have the following code and it works when written like this

byte val = 0;           
int pos = 40;            
int on = 3000;           
int servo_delay;         
byte other = 0;

void setup() 
{
  myservo.attach(9);
  pinMode(SERVO_POWER, OUTPUT);
  Serial.begin(9600); 
}

void loop() 
{
  digitalWrite(SERVO_POWER, LOW);
  if (Serial.available() > 0) 
  { 
   val = Serial.read();
   if (val > 0)
      if (val == '8')
      {  pos = 40; 
         for (int i = 1; i <= 30; i++)
          {  pos = pos + 4;
             digitalWrite(SERVO_POWER, HIGH);
              myservo.write(pos);
             delay(on);
             digitalWrite(SERVO_POWER, LOW);
             servo_delay = 4000-on;
             delay(servo_delay);
             Serial.print(pos);
          }
       }
    }
}

It prints from 40 to 160 and the servo follows. I wanted to add the ability to break the for loop.

So I added the following after the Serial.print(pos);

    if ((Serial.available() > 0) && (val > 0))
             {
             other = Serial.read();
             }
             if ((other = '1') || (other = '2') || (other = '3'))
             {
             break;
             }

After I added this, all I get is 44 from the Serial.print over and over again. Is there something I’m missing here?

thanks!

Perhaps you want:

if ((other == ‘1’) || (other == ‘2’) || (other == ‘3’))

???

Assignment vs. Comparison - the assignment evaluates to TRUE, so it always breaks…

:slight_smile:

Oh…haha…a little lost here why that doesn’t work

but I re-wrote it to:

if ((other >= '1') && (other <= '3'))

and it works, thanks!

a little lost here why that doesn't work

The equals sign "=" in C is an assignment operator. It assigns the value on the right to the variable on the left. If you write an assignment in a conditional like this: if ((a = 3)) {, this is perfectly legal, but the logic goes like this: 1) assign the value 3 to the variable a 2) evaluate the result of this assignment 3) 3 is non-zero, so the condition is true.

oh i didn't notice the difference in our code, = vs. == duh!

thanks