Thursday, 7 May 2026

How to control SG90 Servo using Python on a Raspberry Pi

Wow have I neglected this. But as I have access its a nice place to drop code for those commenting on my YouTube channel. I had a request from the video I did on using the Raspberry Pi to control the SG90 servo and jitter free motion using Python.


So here you go, the code is below:

import RPi.GPIO as GPIO

import time

# Pin configuration

SERVO_PIN = 18  # GPIO 18 for signal

PWM_FREQUENCY = 50  # 50Hz PWM frequency for servos


# Initialize GPIO

GPIO.setmode(GPIO.BCM)  # Use BCM GPIO numbering

GPIO.setup(SERVO_PIN, GPIO.OUT)


# Start PWM

pwm = GPIO.PWM(SERVO_PIN, PWM_FREQUENCY)

pwm.start(0)  # Start with 0% duty cycle


def set_angle(angle):

    """

    Move servo to a specific angle.

    :param angle: Desired angle (0 to 180 degrees)

    """

    duty_cycle = 2 + (angle / 18)  # Map angle to duty cycle (2-12 for SG90)

    pwm.ChangeDutyCycle(duty_cycle)

    time.sleep(0.5)  # Give servo time to move

    pwm.ChangeDutyCycle(0)  # Stop sending signal to avoid jitter


try:

    print("Servo test starting. Use CTRL+C to stop.")

    while True:

        # Move servo to 0°, 90°, and 180° positions

        set_angle(0)

        print("Moved to 0°")

        time.sleep(1)


        set_angle(90)

        print("Moved to 90°")

        time.sleep(1)


        set_angle(180)

        print("Moved to 180°")

        time.sleep(1)


except KeyboardInterrupt:

    print("Test stopped by user. Cleaning up...")

finally:

    pwm.stop()  # Stop PWM

    GPIO.cleanup()  # Reset GPIO settings