ArduinoBeginner

Controlling Servo Motors with Arduino

Learn how to control servo motors using Arduino — from basic sweeps to potentiometer-controlled positioning.

5 January 20269 min read

Introduction

Servo motors are essential in robotics — they allow precise angular positioning. In this tutorial, you'll learn to control a standard servo using Arduino.

Components Required

  • Arduino Uno
  • SG90 Micro Servo Motor
  • 10kΩ Potentiometer (for Part 2)
  • Breadboard and jumper wires

Wiring

Servo WireArduino
Red (VCC)5V
Brown (GND)GND
Orange (Signal)Pin 9

Part 1: Basic Sweep

#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(9);
}

void loop() {
  for (int pos = 0; pos <= 180; pos++) {
    myServo.write(pos);
    delay(15);
  }
  for (int pos = 180; pos >= 0; pos--) {
    myServo.write(pos);
    delay(15);
  }
}

This sweeps the servo from 0° to 180° and back, continuously.

Part 2: Potentiometer Control

Add a potentiometer — connect its middle pin to A0, and the outer pins to 5V and GND.

#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(9);
}

void loop() {
  int val = analogRead(A0);
  int angle = map(val, 0, 1023, 0, 180);
  myServo.write(angle);
  delay(15);
}

Now turning the potentiometer knob directly controls the servo position!

Tips

  • Never power multiple servos directly from Arduino — use an external 5V supply
  • The Servo library disables PWM on pins 9 and 10
  • For continuous rotation servos, write(90) = stop, write(0) = full speed one direction, write(180) = full speed other direction
Tags:ArduinoServoMotor