Menu
CoddyTech

Sweep a Servo

Part of the Outputs section of Coddy's Arduino journey. Lesson 21 of 24.

arm.write() jumps straight to an angle. To move the arm slowly, step through every angle in between with a for loop, waiting a moment at each one:

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

Here the counter is called angle, and <= 180 includes 180 itself. 181 steps of 15 ms take about 2.7 seconds.

To come back, count down. angle-- takes 1 away each round, and the loop runs while the angle is still 0 or more:

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

Put both loops in loop() and the arm sweeps back and forth like a windscreen wiper.

challenge icon

Challenge

Easy

Make the servo on pin 9 sweep, again and again:

  • from 0 up to 180 degrees, one degree at a time, waiting 15 ms at each
  • then back down to 0 the same way

Press Run, then Check.

Try it yourself

#include <Servo.h>

Servo arm;

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

void loop() {
  // sweep from 0 up to 180, one degree every 15 ms
  // then back down to 0
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Outputs

Practice on your own: Arduino playground