Introduction

In this lab, you’ll control a servomotor’s position using the value returned from an analog sensor. Servos are the easiest way to start making motion with a microcontroller. Even though they don’t turn 360 degrees but only 180, you can use them to create all sorts of periodic or reciprocating motions. Check out some of the mechanisms at Rob Ive’s site for ideas on how to make levers, cams, and other simple machines for making motion.

What You’ll Need to Know

To get the most out of this lab, you should be familiar with the following concepts. You can check how to do so in the links below:

Prepare the breadboard

Connect an analog input sensor and a servo

Pick any analog input and connect it to Analog pin 0 as you did in the Analog Input Lab covered previously. Then connect an RC servomotor to digital pin 3. The yellow wire of the servo goes to the pin, and the red and black wires go to +5V and ground, respectively.

Safety Warning! Not all servos have the same wiring colors. For example, the Hextronik servos that come with Adafruit’s ARDX kit use red for +5V,brown for ground, and mustrard yellow for control.

When you attach the servo, you’ll need a row of three male headers to attach it to a breadboard. You may find that the pins don’t stay in the servo’s connector holes. Put the pins in the servo’s connector, then push them down on a table gently. They will slide up inside their plastic sheaths, and fit better in your servo’s connector.

Header pins don't always stay in a servo connector

Put them in and push gently on a firm surface

Voila – your headers fit better!

Program the Microcontroller

First, find out the range of your sensor by using analogRead() to read the sensor and printing out the results.

Finally, add the servo library at the beginning of your code, then make a variable to hold an instance of the library, and a variable for the servo’s output pin. In the setup(), initialize your servo using servo.attach(). Then in your main loop, use servoAngle to set the servo’s position.