Hello, I have made the following code, trying to move 2 servo motors at different speeds so they sweep at the same time. However I have noticed that they can get a bit jittery, so I was wondering if anyone knew how I could fix this, by increasing the speed or the wait time ( I actually have no clue since I've never worked with motors before, if its useful to know, they are sg90 motors ). Any help is appreciated
#include <Servo.h>
Servo servoMotor;
Servo servoMotor2;
unsigned long previousMillis = 0;
const long interval = 40000;
int initialPosMotor = 90;
int initialPosMotor2 = 90;
int maxPosMotor = 100;
int maxPosMotor2 = 150;
int minPosMotor = 90;
int minPosMotor2 = 90;
bool goingBack = false;
void setup() {
Serial.begin(9600);
servoMotor.attach(7);
servoMotor2.attach(8);
}
void loop() {
unsigned long currentMillis = micros();
// Check if enough time has passed
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
int speed = 1;
int x = maxPosMotor - minPosMotor;
int y = maxPosMotor2 - minPosMotor2;
int ratio = abs(y) / abs(x); // ratio for second motor
//initialPosMotor += speed;
if (!goingBack) {
servoMotor.write(initialPosMotor);
servoMotor2.write(initialPosMotor2);
initialPosMotor += speed;
initialPosMotor2 += ratio;
Serial.println("This is the ratio");
Serial.println(ratio);
if (initialPosMotor >= maxPosMotor) {
goingBack = true;
}
}
else {
servoMotor.write(initialPosMotor);
servoMotor2.write(initialPosMotor2);
initialPosMotor -= speed;
initialPosMotor2 -= ratio;
if (initialPosMotor <= minPosMotor) {
goingBack = false;
}
}
Serial.println("This is the first motor");
Serial.println(initialPosMotor);
Serial.println("This is the second motor");
Serial.println(initialPosMotor2);
}
}
The main problem in your sketch are that many Serial.prints() in your loop - especially at 9600 Baud only. These prints slow down your loop significantly, what makes the jitter.
At least use higher baud - e.g. 115200. Or delete the prints at all.
What are you using for a power supply for the servos?
Can you please post a copy of your circuit, a picture of a hand drawn circuit in jpg, png?
Hand drawn and photographed is perfectly acceptable.
Please include ALL hardware, power supplies, component names and pin labels.
humm sooo for this project in particular I am also using a light sensor and 4 RGB LED so the only circuit I have is with all of those, so here is the circuit, ( It's a bit messy and the RGBs dont do the right color, but everything else is working, sorry )