Steps to Control a Servo Motor
1
Open OmniBoard Studio and create a new project.
2
Build the block diagram to sweep the servo from 0° to 180° and back.
Try to build the diagram yourself, or click here to see one solution. ▼
- ● Place a Start block and connect it to a While True block.
- ● Add a Set Servo Angle block set to 0°, followed by a Timer block (e.g. 1000 ms).
- ● Add a second Set Servo Angle block set to 90°, followed by another Timer block.
- ● Add a third Set Servo Angle block set to 180°, followed by a Timer block. The loop will then return to 0° and repeat the sweep.
3
Wire the servo motor to your microcontroller.
- ● A standard servo has three wires: Power (usually red) → connect to 5V, Ground (usually brown or black) → connect to GND, Signal (usually orange or yellow) → connect to a PWM-capable GPIO pin.
- ● Note: if the servo draws too much current, use an external 5V power supply for the servo power wire and share only the ground with the microcontroller.
4
Compile the code and upload it to your microcontroller.
5
Watch the servo arm sweep from 0° to 90° to 180° and back in a continuous loop!
Bonus Information
- Here is simplified MicroPython code for sweeping a servo motor:
import machine
import time
# Servo control on GPIO pin 5 at 50 Hz (standard servo frequency)
pwm = machine.PWM(machine.Pin(5), freq=50)
def set_angle(angle):
# Convert angle (0-180) to duty cycle (approx 40-115 for ESP32)
duty = int(40 + (angle / 180) * 75)
pwm.duty(duty)
while True:
set_angle(0) # Move to 0 degrees
time.sleep(1)
set_angle(90) # Move to 90 degrees
time.sleep(1)
set_angle(180) # Move to 180 degrees
time.sleep(1)
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(5, GPIO.OUT)
pwm = GPIO.PWM(5, 50) # 50 Hz for servo
pwm.start(0)
def set_angle(angle):
duty = 2 + (angle / 18) # Convert angle to duty cycle
pwm.ChangeDutyCycle(duty)
while True:
set_angle(0)
time.sleep(1)
set_angle(90)
time.sleep(1)
set_angle(180)
time.sleep(1)