Servo control code

Hi guys,
I have written a code that is designed to read two push buttons and rotate a servo in a certain direction accordingly. However it doesn’t seem to be doing anything and the servo just seems to have a mind of its own and move varying amounts at varying intervals! If anyone could help me improve the code or get it working it would be much appreciated!
Thanks
Owen

#include <Servo.h> 

Servo myservo;

int left = 8; //Declare pushbuttons
int right = 9;
int leftValue = 0; //Hold left and right button readings
int rightValue = 0;
int servoPos = 50; //Hold servo position

void setup(){
  myservo.attach(10);
  pinMode(left, INPUT_PULLUP);
  pinMode(right, INPUT_PULLUP);
}

void loop(){
  myservo.write(servoPos); //Rotate servo to near middle
  leftValue = digitalRead(left); //Read push buttons
  rightValue = digitalRead(right);
  while(leftValue == HIGH){ //While left one pushed
    servoPos = servoPos - 5; // Servo position -5
    myservo.write(servoPos); // Write new position to servo
    delay(30); // Delay to slow program down
    leftValue = digitalRead(left); // Read button again
  }
  while(rightValue == HIGH){ //While right one pushed
    servoPos = servoPos + 5; // Servo position +5
    myservo.write(servoPos); // Write new position to servo
    delay(30); // Delay to slow program down
    rightValue = digitalRead(right); // Read button again
  }
}

When you use a pull-up resistor, including the internal ones, your pin will read HIGH unless connected to Ground. If you have a typical Normally Open momentary switch between your input pin an Ground the pin will read LOW when the button is pressed and HIGH otherwise. I suspect that by acting on the HIGH signal you are moving the servo back and forth by 5 units UNLESS a button is pushed.

You may want to also check for servoPos going out of range. If servoPos is at 3 and you get the left button pushed you don't want to use a value of -2. I think you should use "servoPos = constrain(servoPos - 5, 0, 180); " to make sure servoPos doesn't go outside the normal limits.

Thanks, changing them from HIGH to LOW got it working as it should. I am not sure if the constraint code you typed was an example or what you meant because I found that didn't work and just confused the program, but servoPos = constrain(servoPos, 0, 180); worked. Just to clarify though does it go inside the while loops or outside as a declaration? Thanks again Owen

It's not a declaration, it's a function.

You can do more than one thing on a line so you can take the lines:

servoPos = servoPos + 5;
servoPos = constrain(servoPos, 0, 180);

and combine them into:

servoPos = constrain(servoPos + 5, 0, 180);

Ok, thanks. :)