Controlling servo motors

A servo motor is a motor that has gears and a feedback system so that it can change its position, controlled by a Pulse Width Modulation signal.

Unlike the motors we have played with earlier, servo motors typically don't spin around over and over again. Instead, they move an arm or lever through an arc, generally 180 degrees. We tell the servo how many degrees to move using Pulse Width Modulation.

The servo motor has circuitry inside that contains a transistor to power the motor. This means we don't need any extra transistor to get more power. We can power the servo motor from a higher voltage battery just like we did in the previous section, by connecting the ground (zero volt) sides of the computer power supply and the servo power supply together.

The servo motor has three wires. They are the power, ground, and control wires. In the photo above, we have connected the power and ground of the computer to the power and ground wires of the servo motor. The remaining wire (the control wire, also called the signal wire) is connected to pin P2.1 in this example. That pin will be driven by Pulse Width Modulation to control how far the little arm on the servo motor will rotate.

The code for controlling servo motors uses a class called Servo. We call the attach method of the servo object to tell it that we are controlling the servo using pin P2_1.

In the loop function, we have two inner loops. The first one counts up to 180, and the second one counts back down to zero. Inside each loop, the loop counter is sent to the servo motor using the write() method on the servo object. Since the servo takes some time to move, we wait for 15 milliseconds after telling it where to go. If we were moving more than one degree, we would probably want to wait longer. Moving 180 degrees all at once might take 50 to 60 milliseconds.

Servo motors can be surprisingly powerful. Because they have gears, the motor can spin fast, and the gears translate that into slow but powerful motion.

Besides rotary servo motors, you can get linear servo motors that move things back and forth in straight lines. You can also get much larger, more powerful servo motors, and run them from more powerful power supplies, in case you need to move something with more muscle.

 

 

Servo Example code