// https://forum.arduino.cc/t/problems-with-the-code-to-use-a-uno-to-control-a-servo-using-a-potentiometer/1409809
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int potpin = A0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
void setup() {
myservo.write(90); // Initialize the servo to the center position
myservo.attach(9); // attaches the servo on pin 9 to the servo object
delay(15); // Small delay to ensure the servo reaches the center position
}
void loop() {
val = analogRead(potpin); // reads the value from the sensor
// Map the potentiometer value (0-1023) to a specific angle range.
// Example: 90 degrees is center. To move 30 degrees each way,
// we map the input from 0-1023 to a range from 60 to 120.
int degree = map(val, 0, 1023, 60, 120);
myservo.write(degree); // sets the servo position
delay(15); // Small delay to make the servo movement smoother5
}