Built-in project · Raspberry Pi 4 Model B

Servo sweep with RPi.GPIO PWM on a Raspberry Pi 4

RPi.GPIO software PWM at 50 Hz on a Raspberry Pi 4: a servo on GPIO18 steps from 0 to 180 degrees and back, one position a second. The whole build, a Raspberry Pi 4 and 1 more part, runs here in your browser on the Python below; open it in the editor to change the wiring or the code and run it again.

Teaching? Assign it to your class in one click.

Beginner Runs in your browser. Free, and no account needed.

The parts retail for about $58. On Mokxi they're free.

Servo sweep with RPi.GPIO PWM · Raspberry Pi 4 Model Blive0.000 s 0.00x
Click to open it in the editor
The circuit itself, running here on the simulator. Press what can be pressed; click anything else to open it in the editor.

The code

The Python exactly as the editor opens it. Change a line there and press Run: the board runs main.py in a Python engine in the page, with gpiozero and RPi.GPIO, and nothing to compile.

main.py · Raspberry Pi 4 Model B
# Sweep a servo with RPi.GPIO's software PWM on a Raspberry Pi 4.
# Signal on GPIO18 (pin 12), power from 5V (pin 2), ground on pin 6.
import RPi.GPIO as GPIO
import time

SERVO = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(SERVO, GPIO.OUT)
pwm = GPIO.PWM(SERVO, 50)        # 50 Hz: one pulse every 20 ms

def angle_to_duty(angle):
    # This servo reads a 0.544 ms pulse as 0 degrees and 2.4 ms as 180.
    pulse_ms = 0.544 + angle / 180 * 1.856
    return pulse_ms / 20 * 100   # the pulse as a percentage of the 20 ms frame

pwm.start(angle_to_duty(90))
try:
    while True:
        for angle in (0, 45, 90, 135, 180):
            pwm.ChangeDutyCycle(angle_to_duty(angle))
            print(f"{angle} degrees: {angle_to_duty(angle):.2f}% duty")
            time.sleep(1)
except KeyboardInterrupt:
    pwm.stop()
    GPIO.cleanup()

Parts list

2 parts, plus the jumper wires. They retail for about $58; on Mokxi they're free.

How it is wired

3 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.

  • Raspberry Pi 4 Model B pin 5V; Hobby servo pin VCC
  • Ground: Raspberry Pi 4 Model B pin GND; Hobby servo pin GND
  • Raspberry Pi 4 Model B pin GPIO18; Hobby servo pin PWM

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.