Servo Motor Interfacing

Servo Motor interfacing with Arduino

A servo motor is an electric device used for precise control of angular rotation. It is used in applications that demand precise control over motion, like in case of control of a robotic arm.
The rotation angle of the servo motor is controlled by applying a PWM signal to it.
By varying the width of the PWM signal, we can change the rotation angle and direction of the motor.
For more information about Servo Motor and how to use it, refer the topic Servo Motor in the sensors and modules section.

Functions Used

1.  Servo myservo
  • This creates an object named myservo of the class Servo.

2.  myservo.attach(pin)
  • This function attaches the servo variable to a pin.
  • Pin is the pin number to which the servo is attached.

3.  myservo.write(angle)
  • This function writes a value to the servo, thus controlling the position of the shaft.
  • Angle can take values between 0 to 180.

4.  map(value, fromLow, fromHigh, toLow, toHigh)
  • This function is used to map a number from one range to another range.
  • This means that “value” having a value between “fromLow” to “fromHigh” gets converted to equivalent values in the range of “toLow” to “toHigh”“fromLow” gets mapped to “toLow” and so on.



Servo myservo;  /* create servo object to control a servo */

int potpin = 1;  /* analog pin used to connect the potentiometer */
int val;    /*  variable to read the value from the analog pin */

void setup() {
  myservo.attach(9);  /* attaches the servo on pin 9 to the servo object */

void loop() {
  val = analogRead(potpin);            /* reads the value of the potentiometer (value between 0 and 1023) */
  Serial.print("Analog Value : ");
  val = map(val, 0, 1023, 0, 180);     /* scale it to use it with the servo (value between 0 and 180) */
  Serial.print("Mapped Value : ");
  myservo.write(val);                  /* sets the servo position according to the scaled value */
  delay(1000);                         /* waits for the servo to get there */