I'm having trouble controlling two servo motors with one analog input

Hi,
I want one servo motor to go from 0 to 90 degrees and then back, and the other to go from 90 to 0 and then back when an analog sensor reads a value of over 125. The servo motor on pin 10 PWM works fine but the servo motor on pin 9 PWM only goes one way and then doesn’t go back until the sensor reads a value of over 125 again. My code is below

#include <Servo.h>

//Define Pins
int servoPin = 9;
int servoPin1 = 10;
int sensorPin = 0;

//Create the Servo Object
Servo myservo;
Servo myservo1;

void setup()
{
 
  //Attaches the Servo to the object
  myservo.attach(servoPin);
  myservo1.attach(servoPin1);
}

void loop()
{
  //Read the Sensor value
  int analogVal = analogRead(sensorPin);
  
  //if the sensor reads over 125 it will turn the servo 90 degrees,
  //wait a second and then turn back
  if (analogVal > 125) {
   myservo.write(90);
   myservo1.write(0);
   delay(1000);
   myservo.write(0); 
   myservo1.write(90); 
  }
}

I have also tried using a boolean in another sketch but that doesn’t work either

#include <Servo.h>

//Define Pins
int servoPin = 9;
int servoPin1 = 10;
int sensorPin = 0;

//Create the Servo Object
Servo myservo;
Servo myservo1;

boolean sensorDown = false;

void setup()
{
 
  //Attaches the Servo to the object
  myservo.attach(servoPin);
  myservo1.attach(servoPin1);
}

void loop()
{
  //Read the Sensor value
  int analogVal = analogRead(sensorPin);
  
  if (analogVal > 125) {
   boolean(sensorDown == true); 
  }
  
  if (sensorDown == true) {
  //if the sensor reads over 125 it will turn the servo 90 degrees,
  //wait a second and then turn back

   myservo.write(90);
   myservo1.write(0);
   delay(1000);
   myservo.write(0); 
   myservo1.write(90); 
  }
}

Try adding this code at the end of the setup function:-

   myservo.write(0);
   myservo1.write(90);
   delay(2000);

Hi Grumpy Mike

I originally had that piece of code in the setup but I took it out and set the servo motors to 0 and 90 in a separate sketch (for my own reasons) so that it wouldn't have to turn the servos each time I hooked up the arduino. It didn't work in the original sketch either btw.

I don't think that it is a coding issue as such. I was told that it could be that the sketch is reading the value from the sensor 9600 times a second and the servo motor is trying to turn and turn again before the sensor levels return to 0, that is why I tried using a boolean instead

In the first code add another delay to allow time for the servos to turn back. As it is they turn you wait a second you give the command to turn and then instantly tell them to go back to where they are already.