Servo keeps returning to 0 after move

My servo reacts as it should and moves to position, but as soon as it’s there it returns back to zero then goes into a loop of this movement.

I have some code that reads the state of a switch. If the switch is low, it moves the servo down to 0. If the switch is high, it moves the servo up to 140.

As it stands, if the switch is low, the servo behaves itself and stays down. If the switch is high, it moves up, but then shoots back down, only to shoot back up again in a continuous loop. I’ve tested switch and that is being read absolutely fine. No issues with it reading that so I can’t for the life of me figure out what’s causing it.

Here’s the code:

MaskButtonState = digitalRead(MaskButton);
EyesButtonState = digitalRead(EyesButton);
  if((servostate == false) && (MaskButtonState == HIGH)){
    digitalWrite(eyes, LOW);
    eyestate = false;
    delay(500);
    for (pos = 70; pos <= 140; pos += 1){
      myservo.write(pos);
    }
    servostate = true;
    MaskButtonState = digitalRead(MaskButton);
  }else if((servostate == true) && (MaskButtonState == LOW){
    for (pos = 140; pos >= 70; pos -= 1){
      myservo.write(pos);
    }
    if(EyesButtonState == HIGH){
    delay(500);
    digitalWrite(eyes, HIGH);
    eyestate = true;
    };
    servostate = false;
    
  }

I wonder if your compound IFs are doing what you think

Try it like this

MaskButtonState = digitalRead(MaskButton);
EyesButtonState = digitalRead(EyesButton);
if(servostate == false) {
    if(MaskButtonState == HIGH)){
        digitalWrite(eyes, LOW);
        eyestate = false;
        delay(500);
        for (pos = 70; pos <= 140; pos += 1){
          myservo.write(pos);
        }
        servostate = true;
        MaskButtonState = digitalRead(MaskButton);
    }
}
}else if(servostate == true) {
    if (MaskButtonState == LOW){
        for (pos = 140; pos >= 70; pos -= 1){
          myservo.write(pos);
        }
        if(EyesButtonState == HIGH){
            delay(500);
            digitalWrite(eyes, HIGH);
            eyestate = true;
        };
        servostate = false;
    }
}

I am not claiming to have done things correctly, but the errors should be more obvious. And you can insert Serial.print() statements to watch what it is doing.

…R

Good idea. Unfortunately I'm now away from my workshop for a few days over Christmas but I'll try this when I'm van next week..

Thanks for the suggestion.