Lesson 14 / 25

Servos and Stepper Motors

Position control without feedback code.

Two ways to control position

A hobby servo contains a motor, gearbox, position sensor and control circuit. You send a pulse roughly every 20 ms whose width (about 1 to 2 ms, varying by model) sets the angle; the Arduino Servo library generates this signal on any digital pin. On the Uno R3 the Servo library uses Timer1, which disables analogWrite on pins 9 and 10. A stepper motor moves in fixed steps by energising coils in sequence, giving open-loop positioning for 3D printers and CNC. Drive steppers through a driver: a ULN2003 board for small unipolar motors like the 28BYJ-48, or a STEP/DIR driver such as an A4988 or DRV8825 for bipolar motors (set the current limit as the driver's documentation describes). Power both servos and steppers from a separate supply, not the board's 5 V pin, with grounds connected.

Sweep a servo with the Servo library

Signal on pin 9; servo power from an external 5-6 V supply (check the servo's rating) with ground shared.

#include <Servo.h>

Servo arm;
int angle = 0, step = 2;
unsigned long last = 0;

void setup() {
  arm.attach(9);           // signal pin
  arm.write(90);           // centre
}

void loop() {
  if (millis() - last >= 15) {
    last = millis();
    arm.write(angle);      // 0..180 degrees
    angle += step;
    if (angle <= 0 || angle >= 180) step = -step;
  }
}

Thermostat versus counting stairs

A servo is like a thermostat: you set a target and it corrects itself. A stepper is like walking up stairs by counting steps: precise as long as you never miss one.

Quick check: What sets the angle of a typical hobby servo?

  • The ADC reference
  • The supply voltage level
  • The number of I2C bytes sent
  • The width of a repeating control pulse
Answer

The width of a repeating control pulse — Roughly 1-2 ms pulses about every 20 ms map to the servo's range.