Arduino servo and ultrasonic sensor coding trouble

  • Hello, I'm trying to make an obstacle-avoiding robot using an ultrasonic sensor and 2 servos. and when my sensor kicks in I just want one leg to move but the right still moves but in a delay. What can I do to fix this?


  • AD
  • Create a separate function that controls your servo first. No reason to dublicate your code multiple times.

    Code
    void moveServos(int servo1Position, int servo2Position)
    {
        // from your global variable use your servo objects
        myservo1.write(servo1Position);
        myservo2.write(servo2Position);
    }

    As I understood you have a small cart or else. Each servo controls it's own side - left/right. In this case you always control both sides. Then modify your logic upfront to do calculation for 2 servos always and you wont have any issues. If you want to delay for one of the servos, then send same position and you wont have issues. You need to reorganize part of your code(below) to make calculation always for both legs to make sure that you wont have any issues whatever leg you are using at the moment.

    Code
    if(distance_cm < DISTANCE_THRESHOLD) {
    for (pos = 0; pos <= pos3; pos += 1) { 
      myservo1.write(pos);
      delay(15);
    }
      for (pos = pos3; pos >= 0; pos -= 1) { 
      myservo1.write(pos);
      delay(15);
      }
    }

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account
Sign up for a new account in our community. It's easy!
Register a new account
Sign in
Already have an account? Sign in here.
Sign in Now