title | layout | meta-description | share | author | about | cats | simple-description | date |
---|---|---|---|---|---|---|---|---|
How to Use Servos on the Microbit |
text-width-sidebar |
Add the servo Python module to control a servo. Examples using the microbit with servo, potentiometers and LED lights. |
true |
jez |
Examples of using a servo with the microbit for use in physical projects. |
component examples |
Servo Examples |
2016-12-23 10:20:00 UTC |
""" Unchecked.
There are a few PWM issues. """
These examples us the The Tower Pro SG90 servo. This is a 180° servo meaning it can turn from 0° to 180°.
See the component article on this website about how to use the servo.
{:.ui .header .dividing}
- 3.3v Servo
Moving the microbit causes the servo to rotate.
{% highlight python %} from microbit import *
from servo import Servo
def rescale(src_scale, dest_scale, x): src_start, src_end = src_scale proportion = 1.0 * (x - src_start) / (src_end - src_start) dest_start, dest_end = dest_scale return proportion * (dest_end - dest_start) + dest_start
while True: # rescale accelerometer x axis to between 0 and 180 rescaled_angle = rescale( (-1023, 1023), (0, 180), accelerometer.get_x())
Servo(pin0).write_angle(rescaled_angle)
sleep(200)
{% endhighlight %}
{:.ui .header .dividing}
- 3.3v Servo
- 10k Potentiometer
Turning the potentiometer causes the servo to rotate.
See the component article for a potentiometer for more.
{% highlight python %} from microbit import *
from servo import Servo
def rescale(src_scale, dest_scale, x): src_start, src_end = src_scale proportion = 1.0 * (x - src_start) / (src_end - src_start) dest_start, dest_end = dest_scale return proportion * (dest_end - dest_start) + dest_start
servo1 = Servo(pin0) pot_reading = pin1.analog_read()
while True: # rescale pot reading (0 - 1023) to servo angle (0 - 180) rescaled_angle = rescale( (0, 1023), (0, 180), pot_reading)
servo1.write_angle(rescaled_angle)
sleep(200)
{% endhighlight %}
{:.ui .header .dividing}
- 3.3v Servo
button_a
and button_b
control the rotation of the servo. Be sure to upload the servo class in mu.
{% highlight python %}
from microbit import *
from servo import Servo
angle = 0
Servo(pin0).write_angle(angle)
while True: if button_a.was_pressed and (angle <= 180): angle = angle + 10 Servo(pin0).write_angle(angle)
if button_a.was_pressed and (angle >= 0):
angle = angle - 10
Servo(pin0).write_angle(angle)
sleep(10)
{% endhighlight %}