Ask a parent, teacher, or trusted adult before building, powering a circuit, using tools or batteries, or buying parts. Purchases are optional and at your own cost. If anything gets hot, smells burnt, leaks, swells, sparks, or moves unexpectedly, switch off or disconnect power without touching the damaged or hot part, then tell an adult. Read safety rules

All code examples

Servo sweep — Arduino code

A servo moves to an angle you choose and holds it there. Two sketches cover almost everything: one that jumps to set angles, and one that sweeps smoothly from 0° to 180°.

What you need

  • • Arduino Uno
  • • 1 × SG90 micro servo
  • • 3 jumper wires

Wiring

Test code virtually first. For real hardware, ask a trusted adult, unplug power before changing wires, and check the labels or datasheet for your exact part.

  1. 1Brown or black servo wire to GND.
  2. 2Red servo wire to a regulated 5 V supply sized for your exact servo; do not connect an unknown battery directly.
  3. 3Join the servo supply GND to Arduino GND, and disconnect power before changing wires.
  4. 4Orange or yellow signal wire to digital pin 9.

The code

servo-motor.ino
#include <Servo.h>

Servo arm;

void setup() {
  arm.attach(9);   // signal wire on pin 9
}

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

Line by line

#include <Servo.h>
Loads the built-in Servo library — no download needed.
Servo arm;
Creates a servo object you can command by name.
arm.attach(9);
Connects that object to the signal pin.
arm.write(angle);
Moves the horn to that angle in degrees, 0 to 180.
delay(15);
Gives the servo time to reach each step, which makes the sweep smooth.

When it does not work

My servo jitters or resets the board
It may be drawing more current than the board can supply. Unplug it, ask an adult to use a suitable regulated 5 V supply, and join that supply's ground to Arduino GND. Stop if the servo is hot, stalled, or buzzing hard.
How do I hold one exact angle?
Delete the loops and call arm.write(90); once inside setup() — the servo will move there and stay.
Which pins work for servos?
Any digital pin works with the Servo library, but pins 9 and 10 are the usual choice on an Uno.

Want the theory behind it?

More code examples