| title | Using a servo with the microbit |
|---|---|
| layout | text-width-sidebar |
| meta-description | Use a servo in python with the microbit. |
| share | true |
| author | jez |
| about | Use a servo in python and PXT. |
| cats | external |
| simple-description | Servo |
| acknowledgements | Servo teaser & diagram by [Upgrade Industries](https://www.upgradeindustries.com/licensing/) |
| date | 2016-12-23 10:20:00 UTC |
| date-updated | 2016-12-23 10:20:00 UTC |
The Tower Pro SG90 is a small, 9 gram servo that can run directly from the microbit power supply. This is a 180° servo meaning it can turn from 0° to 180°. It has many applications: open a flap to dispense treats for to a dog, create a robotic walker, or to drive window wipers on a car.
{:.ui .dividing .header}
Most servos have three wires: GND, POWER, and SIGNAL.
Wire colours differ based on manufacturer. Here's the Tower Pro servo; look at the wire colours:
Information about the wire colours can be found in the datasheet. This can be found by Googling SG90 datasheet:
We now know how to connect the servo:
{:.ui .very .basic .small .table}
| Servo Wire Colour | Data Sheet Label | Connect to Microbit Pin |
| Red | VCC (+) | 3V pin |
| Brown | Ground (-) | GND pin |
| Orange | PWM (Signal) | pin0 |
The angle of the servo is set by a PWM pulse to the orange wire. This is connected to pin0.
{:.ui .dividing .header}
Servos are difficult to control in Python on the microbit. I've tried to make it easy below.
A module must be installed to tell Python how to use the servo.
- Download the Servo class and save it in the
/mu_codedirectory in your home folder. - Upload the code below to your microbit.
- Upload the
servo.pyfile to the microbit within mu.
There are detailed instructions on adding a module to the microbit on this website.
{% highlight python %}
from microbit import *
from servo import Servo
while True: Servo(pin0).write_angle(0) sleep(200) Servo(pin0).write_angle(90) sleep(200) Servo(pin0).write_angle(180) sleep(200)
{% endhighlight %}
The angle of the servo is controlled by Servo(pin0).write_angle(30). If you want to control a servo attached to pin1 as well, it would be:
{% highlight python %} Servo(pin1).write_angle(30) {% endhighlight %}
We can also make this a variable for ease of use:
{% highlight python %} sv1 = Servo(pin0) sv2 = Servo(pin1)
sv1.write_angle(180) sv2.write_angle(0) {% endhighlight %}
- Play with the sweep example to rotate the servo through 180°


