Ready-to-teach lab

Arduino servo lab: sweep to an angle

This Arduino servo lab moves a hobby servo on pin 9 to 0, 90 and 180 degrees and then sweeps it back a degree at a time, which introduces libraries, for loops and position control.

Ages 12 and up, robotics or mechatronics. About 40 minutes. Students read and change an Arduino sketch.

The lesson

Objective and parts

By the end, students can

  • Use the Servo library: attach a servo and write an angle to it.
  • Read a small function, moveTo, and say why the sketch has one.
  • Use a for loop to move in small steps.
  • Describe how the width of a pulse tells a servo where to point.

Parts, already on the bench

  • An Arduino Uno
  • One hobby servo: signal on pin 9, power on 5 V, and ground

Nothing to hand out or collect: the circuit opens built and wired.

Steps

What students do

Each step is short enough to read out. Students work in the simulator beside this page.

  1. Open the lab and press Run. The horn steps to 0, 90 and 180 degrees, waits a second at each, then sweeps back.
  2. Open the serial monitor to see each angle as the sketch sends it.
  3. In the code, find the for loop that does the sweep. How long does each one-degree step wait?
  4. Make the sweep back take about twice as long.
  5. Make the servo stop at 45 and 135 degrees as well.
  6. Write a sweep that goes forward from 0 to 180 one degree at a time, as the one coming back does.
Questions

Questions for students

Hand these out as they are. The expected answers are under the list, for you.

  1. What do horn.attach(9) and horn.write(90) do?
  2. The sweep waits 10 ms after each degree. About how long does 180 degrees take?
  3. How does the servo know which angle is wanted?
  4. How is a servo different from an ordinary DC motor?
Answer key for the teacher
  1. attach tells the library which pin the signal wire is on. write(90) asks the servo to turn to 90 degrees, the middle of its travel.
  2. About 1.8 seconds: 180 steps of 10 ms.
  3. The board sends a pulse 50 times a second. The width of the pulse, from about 0.5 ms to about 2.4 ms, sets the angle.
  4. A DC motor spins for as long as it has power. A servo turns to a position and holds it, using a sensor inside to check where it is.
Go further

For students who finish early

  • Add a potentiometer and make the servo follow the knob.
  • Use two servos to make a pointer that moves up and down and side to side.
Your class

Give this lab to every student

Assign to my class puts this circuit on each student’s class page as a starter. They change their own copy and hand it in, and the work comes back to you in one list.

The class tools are free for 30 days for one class of up to 20 students, with no card. Opening and running the lab needs no account and stays free.