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;
}