CYTHEIA AIOpen the editor

Servo Sweep

Servo motor sweeping back and forth 0 to 180 degrees.

Open this circuit and run it

Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.

How it works

A servo is a small motor that turns to a position you command, from 0 to 180 degrees. It has three wires: power (5V), ground, and a signal wire that carries the position command. Here the signal wire is on pin 9.

The sketch uses the Servo library: myservo.attach(9) ties the servo to pin 9, and myservo.write(pos) turns it to an angle. loop() steps the angle up from 0 to 180 one degree at a time, pausing 15 milliseconds between steps, then steps it back down to 0. The upward sweep also prints each angle to the Serial tab.

Parts

Wiring

Arduino code

// Servo Sweep
#include <Servo.h>

Servo myservo;
int pos = 0;

void setup() {
  myservo.attach(9);
  Serial.begin(9600);
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) {
    myservo.write(pos);
    Serial.print("Angle: ");
    Serial.println(pos);
    delay(15);
  }
  for (pos = 180; pos >= 0; pos -= 1) {
    myservo.write(pos);
    delay(15);
  }
}

Try changing it

Open this circuit and run it

Next challenge

More projects in Motors