This code controls the rotation of the Servo motor by the rotation of the potentiometer.
#include <Servo.h>;
We start by including the Servo library, which has all the essential header files to control the
servo motor.
Servo myServo;
We create a variable myServo to control the Servo Motor.
int potpin = A0;
We have used analog pin A0 to connect the potentiometer.
int val;
Here, we have created a variable to read the data from the analog pin A0.
void setup()
{
Serial.begin(9600);
myServo.attach(9);
}
In the setup function, we start serial communication with a baud rate of 9600 and attach the
servo motor to pin9 of Arduino.
void loop()
{
val = analogRead(potpin);
In the loop function, we first read the potentiometer value using analogRead() function, which
returns a value between 0 to 1023.
int angle = map(val, 0, 1023, 0, 180);
We create a variable angle to store the servo motor angle value.
Also, we map the potentiometer value from the range of 0 to 1023 to the range of 0 to 180
(which is the range of servo motor angles).
myServo.write(angle);
We then use the write() function of the Servo library to set the angle of the servo motor to the
mapped value.
Serial.print("Potentiometer value:");
Serial.print(val);
Serial.print(", angle:");
Serial.println(angle);
Finally, we use the Serial.println() function to print the potentiometer value and the
corresponding angle to the serial monitor.
delay(15);
}
This is the delay time taken by the servo motor to reach the new position.