Skip to content

Servo Motor

Level Intermediate
Board V1 & V2
Parts micro:bit · SG90 (9g) servo motor · Jumper wires
Copy first servo.py onto your micro:bit before flashing the example — how?

What you'll build

Press button A to turn the servo to 90°, button B to return it to 0°.

Wiring

Part Part pin micro:bit pin
SG90 servo Signal (orange) P0
SG90 servo Power (red) 3V (or an external 5 V supply for heavier loads)
SG90 servo Ground (brown) GND
SG90 servoSignal (orange)Power (red)Ground (brown)micro:bitP03VGND

Code

servo-example.py
'''
Example: Controlling Servo Motor 9g example using micro:bit
By: Meqdad Darwish
'''
from microbit import *
from servo import Servo

my_servo = Servo(pin0)

while True:
    if button_a.was_pressed():
        my_servo.set_angle(90)
        display.scroll(90)
    if button_b.was_pressed():
        my_servo.set_angle(0)
        display.scroll(0)
servo.py
'''
Servo Motor (9g) Module in microPython for the microcontrollers like micro:bit
Author: Meqdad Darwish
GitHub: @MeqdadDev
https://github.com/MeqdadDev/
'''

from microbit import *


class Servo:
    '''
    A library to interface Servo motor 9g in microPython with micro:bit.

    Example:
    ```py
    from microbit import *
    from servo import Servo

    my_servo = Servo(pin0)
    my_servo.set_angle(90)
    ```
    '''

    def __init__(self, pin=pin0):
        self.pin = pin

    def set_angle(self, angle=0):
        duty = 26 + (angle * 102) / 180
        self.pin.write_analog(duty)

How it works

Hobby servos read the width of a repeating pulse to choose their angle. set_angle() maps 0–180° onto an analog duty value and writes it with pin.write_analog().

Try this next

  • Sweep smoothly from 0° to 180° in a loop.
  • Control the angle by tilting the board with accelerometer.get_x().
  • Build a pointer that shows the temperature on a dial.