Hi. I have this problem, my servo moves continuously even after the set angle it must reach. My circuit is as follows, I have an Esp32 with a webserver that has a joystick that sends commands to an arduino Uno, I want to control the direction of a car with an SG90 Servo. The direction is ok when I move the jpystick left and right, but the problem is that it does not stop at the set angle, but goes further. If I hold the right or left Joystick it goes continuously. Below I have put the code I am using now.
Thank you in advance!
#include <AFMotor.h>
#include <ArduinoJson.h>
#include <Servo.h>
// Motor control setup
AF_DCMotor motorLeft(3); // Motor (back-left)
AF_DCMotor motorRight(4); // Motor (back-right)
// Servo control setup
Servo steeringServo;
const int servoPin = 9; // Pin connected to the servo
// Serial communication variables
const size_t bufferSize = 200;
char serialBuffer[bufferSize];
size_t bufferIndex = 0;
bool dataReady = false;
// Current servo position
int currentServoPosition = 90; // Initial position (center)
// Previous x value for comparison
int prevX = -1;
void setup() {
Serial.begin(115200);
// Motor control setup
motorLeft.setSpeed(0); // Initialize motor speed to 0
motorRight.setSpeed(0);
motorLeft.run(RELEASE); // Initialize motor state to released
motorRight.run(RELEASE);
// Servo setup
steeringServo.attach(servoPin);
steeringServo.write(currentServoPosition); // Set initial position to default (center)
Serial.println("Arduino Uno setup complete");
}
void loop() {
// Read data from Serial
while (Serial.available()) {
char receivedChar = Serial.read();
if (receivedChar == '{') {
bufferIndex = 0; // Start of new JSON object
}
if (bufferIndex < bufferSize - 1) {
serialBuffer[bufferIndex++] = receivedChar;
}
if (receivedChar == '}') {
serialBuffer[bufferIndex] = '\0'; // Null-terminate the string
dataReady = true;
}
}
// Process received data
if (dataReady) {
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, serialBuffer);
if (error) {
Serial.print("Failed to parse JSON: ");
Serial.println(error.c_str());
} else {
int x = doc["x"];
int y = doc["y"];
int angle = doc["angle"];
// Serial.print("Received data: x: ");
// Serial.print(x);
// Serial.print(", y: ");
// Serial.print(y);
// Serial.print(", angle: ");
// Serial.println(angle);
controlMotors(y);
controlSteering(x);
}
dataReady = false;
}
}
void controlMotors(int y) {
int motorSpeed = 255; // Set a fixed motor speed
if (y > 0) {
// Forward
motorLeft.setSpeed(motorSpeed);
motorRight.setSpeed(motorSpeed);
motorLeft.run(FORWARD);
motorRight.run(FORWARD);
} else if (y < 0) {
// Backward
motorLeft.setSpeed(motorSpeed);
motorRight.setSpeed(motorSpeed);
motorLeft.run(BACKWARD);
motorRight.run(BACKWARD);
} else {
// Stop
motorLeft.run(RELEASE);
motorRight.run(RELEASE);
}
}
void controlSteering(int x) {
// Map the joystick x value (0 to 100) to servo angle (0 to 180 degrees)
int servoAngle = map(x, 0, 100, 0, 180);
}