Introduction to Python and Microcontrollers

Servo Sweep

Make a servo motor sweep continuously from 0° to 180° and back.

New Concepts

Servo

A servo packages a small DC motor, reduction gears, a position sensor, and control circuitry together, letting you command it to a specific angle (rather than just spinning continuously like the DC motor). Most hobby servos sweep a 180° range via their output “horn,” and can output far more torque than a bare DC motor of similar size.

Servo component

Controlling a servo with PWM signal

A servo has 3 wires: power (red, VCC), ground (brown, GND), and signal (orange). It’s positioned with a 50Hz PWM signal, where the pulse width (not the duty cycle percentage) determines the angle:

Pulse width Servo angle
0.5ms
1.0ms 45°
1.5ms 90°
2.0ms 135°
2.5ms 180°

Component List

Components


Circuit

Servos need a clean 5V supply — double-check polarity before connecting power.

Wiring Diagram

Disconnect all power before building the circuit. Reconnect once verified.

Wiring Diagram

Connections:

Schematic Diagram

Schematic Diagram

Code

File: 04_output/code/Servo_Sweep.py Module: 04_output/code/myservo.py

from myservo import myServo
import time

servo=myServo(21)#set servo pin
servo.myServoWriteAngle(0)#Set Servo Angle
time.sleep_ms(1000)

try:
    while True:       
        for i in range(0,180,1):
            servo.myServoWriteAngle(i)
            time.sleep_ms(15)
        for i in range(180,0,-1):
            servo.myServoWriteAngle(i)
            time.sleep_ms(15)        
except:
    servo.deinit()

How to Run

Online

  1. Open Thonny → 04_output/code/.
  2. Right-click myservo.pyUpload to / — wait for it to finish uploading to the ESP32-S3.
  3. Double-click Servo_Sweep.py.
  4. Click Run current script — the servo sweeps from 0° to 180° and back, repeatedly.

Code Explanation

Create the servo object and set a starting angle

servo=myServo(21)
servo.myServoWriteAngle(0)
time.sleep_ms(1000)

myServo(21) configures PWM on GPIO21 at the servo’s expected 50Hz. Setting it to 0° first and waiting a second gives the servo time to physically reach that position before the sweep starts.

Sweep up, then down

for i in range(0,180,1):
    servo.myServoWriteAngle(i)
    time.sleep_ms(15)
for i in range(180,0,-1):
    servo.myServoWriteAngle(i)
    time.sleep_ms(15)

Each loop steps the angle one degree at a time with a short pause, producing a smooth sweep rather than an instant jump (the same “ramp gradually” idea as Breathing LED’s PWM fade, just applied to angle instead of brightness).

Release the servo

except:
    servo.deinit()

Key Concepts

See class myServo for the full API reference.

Further Exploration

Back to Module

Adapted from Python_Tutorial.pdf Project 18.1