Random change of angles of servo motors

I'm currently working on a project which uses 3 servo motors (TD-8320MG), an ultrasonic sensor and a force sensor, they're connected to an arduino uno. Basically, servo 1 moves independently and only 90 degrees while servo 2 and 3 are a mirror of each other and move simultaneously at certain angles. During testing, the servos move as expected but at times, servo 2 and 3 would suddenly change angles. I've tried editing the code but just couldn't find out what was wrong so I need a little help. Are there any issues with my code or may it be due to the loop that resets?

#include <Servo.h>
Servo servo1;
Servo servo2;
Servo servo3;
int trigPin = 8;
int echoPin = 9;
long distance;
long duration;

void setup() 
{
pinMode(A0,INPUT);
  
servo1.attach(10); 
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 
 servo2.attach(11); 
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
  
 servo3.attach(12); 
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
  
 Serial.begin(9600);
}
 
void loop() {
  int sensorvalue = analogRead(A0);
  sensorvalue = analogRead(A0);
  
  Serial.print("Weight: ");
  Serial.println(sensorvalue);

  ultra();
  servo1.write(0);
  servo2.write(0);
  servo3.write(0);
  if(distance <= 50 && sensorvalue < 500){
  servo1.write(90);
  servo2.write(0);
  servo3.write(90);
  }
    else if(distance > 60 && sensorvalue > 500){
  servo1.write(0);
  servo2.write(0);
  servo3.write(90);
  }
  
  else if(distance <= 50 && sensorvalue > 500){
  servo1.write(90);
  servo2.write(30);
  servo3.write(60);
  }
  
    else if(distance > 60 && sensorvalue < 500){
  servo1.write(0);
  servo2.write(0);
  servo3.write(90);
  }
  delay(1000);
}
 
void ultra(){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration*0.034/2;
  }

Why do this three times?
Don't you trust the compiler?

If it were me I would do it four times just in case.

And I'd write trigPin LOW, and lose a couple of lines from ultra ().

1 Like

One thing to remember is that analog values can bounce even with a relatively stable input.

1 Like

You need to power the servos independently of the Arduino if you already haven't. The voltage drop moving a servo will cause it to reset.

1 Like

Do you have to read this twice in a row?

Check your logic and you will see that

  • When the distance is between 50 and 60, no action is taken
  • When distance is > 0, the same actions are taken regardless of the weight

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.