Skip to content

Part 5: Controlling a Positional Servo Motor with PWM

A positional servo interprets repeating pulse widths as a requested position. Start with a supported centre pulse and small changes, not an automatic sweep to mechanical limits.

Sample code on GitHub

Sample and README · C++ source · CMake build instructions

The repository's CMake target is servo_plan; its source file is named main.cpp. The direct-build instructions below remain available. Reuse the shared PWM sample for actual pulses; the calculator itself performs no hardware I/O.

Before you start

Complete Hardware PWM, including controller/channel identification and building pwm_pulse. This lesson reuses that program, so its export, error handling and cleanup policy stay consistent.

You need a documented positional servo, a regulated external supply within its voltage rating, suitable wiring, and a verified 3.3 V-compatible signal input. The example component is FEETECH FS90, not FS90R. Confirm the exact part and revision.

Run builds/commands on the Pi. You can compile the pulse calculator and use planning mode without connecting a motor. Actual movement is an optional bench test requiring electrical and mechanical checks.

1. Understand pulse width, period and position

For this example, use a 20 ms period (50 Hz) and a nominal 1500 μs centre command:

1
2
3
period = 20 ms = 20,000,000 ns
high time = 1500 μs = 1,500,000 ns
duty ratio = 1,500,000 / 20,000,000 = 7.5%

The high time is the command; the duty percentage is derived from it. Do not confuse changing the period with changing position.

The FS90 manufacturer's specification lists its voltage and pulse-range characteristics. Those ranges are not universal servo limits. Do not assume 500/1500/2500 μs always means exact 0/90/180 degrees, or that a labelled “180 degree” servo can safely traverse that range in an attached mechanism.

Centre and angle require calibration of the actual servo, horn and load. Open-loop pulse commands do not report the achieved angle to the Pi.

2. Use external motor power from the beginning

Shut down and disconnect both Pi and servo power before wiring. Remove the buzzer circuit from GPIO12.

For the Pi 4 GPIO12/PWM route established in the previous lesson:

1
2
3
Pi physical pin 32 (GPIO12) ── servo signal input
Pi physical pin 6 (GND) ────── external supply negative ── servo ground
External supply positive ──── servo power

Do not connect the external supply positive to the Pi's 5 V or 3.3 V pins. The supplies share a ground reference, not their positive rails. Do not power the motor from a GPIO signal or the Pi's 3.3 V rail.

For FS90, the manufacturer specifies 4.8–6 V operation and a substantially larger stalled current than idle current. Choose the supply, connectors and wiring for the actual stall/transient requirement with margin. A motor is not made safe by supplying only its average current.

Wire colours differ; identify signal, positive and ground from the actual component. Confirm its input recognises 3.3 V logic. If a level interface is required, use a suitable design that does not feed 5 V back into the Pi.

Movement can start with the first valid pulse

Secure the servo body, disconnect external mechanisms and keep hands clear. Remove the horn for initial centring if appropriate. A 1500 μs pulse can still cause immediate motion from an unknown starting position. Keep an accessible way to cut motor power.

Avoid driving a powered-off servo input or leaving its signal in an undefined state. Follow the component's specified power sequence and disconnect power before changing wires.

3. Compile a pulse calculator without hardware access

Save as servo_plan.cpp:

#include <iostream>
#include <stdexcept>
#include <string>

int main(int argc, char* argv[])
{
    try {
        if (argc != 2) throw std::runtime_error("Usage: servo_plan PULSE_US");
        const std::string text(argv[1]);
        std::size_t used = 0;
        const int pulse_us = std::stoi(text, &used);
        if (used != text.size() || pulse_us < 1000 || pulse_us > 2000)
            throw std::runtime_error("This exercise permits 1000..2000 microseconds.");
        constexpr int period_ns = 20'000'000;
        const int duty_ns = pulse_us * 1000;
        std::cout << "period_ns=" << period_ns << '\n'
                  << "duty_ns=" << duty_ns << '\n'
                  << "duty_percent=" << 100.0 * duty_ns / period_ns << '\n';
        return 0;
    } catch (const std::exception& error) {
        std::cerr << error.what() << '\n';
        return 1;
    }
}
g++ -std=c++17 -Wall -Wextra -Wpedantic servo_plan.cpp -o servo_plan
./servo_plan 1500

Check: output is 20,000,000 ns period, 1,500,000 ns high time and 7.5 percent duty. The 1000–2000 μs guard is a software exercise boundary, not certification that that whole range is safe for your servo.

The program converts units and checks input; it does not operate GPIO, measure an angle or calibrate a motor. Use the actual component's safe limits even if this calculator accepts a value.

4. Plan a short centre pulse first

Use the confirmed controller/channel from the PWM lesson. In the directory containing pwm_pulse:

./pwm_pulse /sys/class/pwm/pwmchipN 0 20000000 1500000 1000

Check: a one-second hold with the intended period/high time; no hardware opened. Do not substitute an arbitrary pwmchip0 just because a different system used it.

Only after the wiring, power, signal compatibility and mechanical checks, apply the centre test:

sudo ./pwm_pulse /sys/class/pwm/pwmchipN 0 20000000 1500000 1000 --apply

Observe from a safe distance. Expected: the unloaded servo seeks its nominal centre, then the PWM program disables/unexports the channel on completion. The shaft may lose holding torque after pulses stop. Do not test with a load that could fall or cause injury.

If it buzzes continuously, hits a stop, heats, draws unexpected current or resets the Pi, cut motor power and investigate. Do not “fix” a stalled motor by increasing pulse range.

5. Try a small change, not a full sweep

Once centre behaviour is understood, and only within your component's documented limits, plan a small variation:

./servo_plan 1400
./pwm_pulse /sys/class/pwm/pwmchipN 0 20000000 1400000 500

Review the values, then apply that same finite command if appropriate. Return with the centre test when required; do not assume an exact angle for a 100 μs change.

For repeatable control, measure several safe pulse/angle pairs, record supply/load conditions and keep margins from mechanical stops. Calibration belongs before attaching a mechanism or accepting arbitrary user-supplied angles.

Troubleshooting

Symptom Check
No movement Actual power at servo, common ground, signal compatibility and controller route
Jitter or Pi resets Supply, current peaks, grounding and signal; do not blame scheduling before inspecting hardware PWM
Unexpected endpoint Wrong model, unit conversion, calibration or requested range
Motor strains or heats Cut power; inspect load/stops rather than forcing motion
PWM program reports cleanup failure Local inspection and safe motor power removal
Servo drifts after program exits Holding signal removed; plan for the mechanism rather than expecting a powered lock

The C++ calculator and shared PWM program are compiled and software-tested. No revised servo wiring or physical movement test was performed for this revision. A simulated PWM filesystem does not prove electrical timing or position.

The earlier positional-servo video is retained as historical demonstration footage, not a test of the new procedure.

Practice before the next lesson

Run the software-only servo_plan calculator with 1600 μs. Predict duty_ns and duty_percent for the 20 ms period. Can that result tell you the real servo's angle? Do not send pulses to a motor for this exercise.

Hint and expected result

1600 μs = 1600000 ns; 1600000 / 20000000 × 100 = 8%. This is a unit conversion, not an angle measurement or safe-range calibration. Keep the motor disconnected and do not add --apply to a shared PWM command.

Check your understanding and continue

Why are the two supplies' grounds connected but positive rails separate? Why is 7.5% meaningful only together with its period? What could happen to a load when pulses stop?

Next, read Continuous Rotation Servo Control, where pulse width commands speed/direction rather than position.

Donate