#include <Servo.h>
Servo myServo; // create a servo object
int feedbackPin = 0; // analog input pin to read feedback signal
int targetAngle = 90; // target angle for the servo
int feedbackValue; // variable to store feedback signal
void setup() {
myServo.attach(9); // attach the servo to pin 9
Serial.begin(9600); // initialize serial communication
}
void loop() {
feedbackValue = analogRead(feedbackPin); // read the feedback signal
int currentAngle = map(feedbackValue, 0, 1023, 0, 180); // map the feedback signal to an angle value
int error = targetAngle - currentAngle; // calculate the error between target and current angle
int offset = map(error, -90, 90, -30, 30); // map the error to a servo offset value
int servoPos = targetAngle + offset; // calculate the new servo position
myServo.write(servoPos); // set the servo position
delay(10); // wait for the servo to move
Serial.print("Target Angle: ");
Serial.print(targetAngle);
Serial.print("\t Current Angle: ");
Serial.print(currentAngle);
Serial.print("\t Error: ");
Serial.print(error);
Serial.print("\t Servo Position: ");
Serial.println(servoPos);
}
Comments