Using a Servo with the MicroBit

While I am very prepared to praise all aspects of the MicroBit for its ease of use, utility, and ability to inspire and engage, I curse its interaction with servos under my breath.

There may be a simpler way to use the servo, and if there is I would love to see it.  Until then, this is the what I came up with, and it seems to work for me.

Step One:  Load a Python Program

The python program below contains a Class called Servo.  Once that is loaded, it seems like you can very easily use the Servo pins in the Javascript Blocks.  The MicroBit does not come ready to use the Class Servo.


from microbit import *

class Servo:
  def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180):
    self.min_us = min_us
    self.max_us = max_us
    self.us = 0
    self.freq = freq
    self.angle = angle
    self.analog_period = 0
    self.pin = pin
    analog_period = round((1/self.freq) * 1000) # hertz to miliseconds
    self.pin.set_analog_period(analog_period)

  def write_us(self, us):
    us = min(self.max_us, max(self.min_us, us))
    duty = round(us * 1024 * self.freq // 1000000)
    self.pin.write_analog(duty)
    self.pin.write_digital(0) # turn the pin off

  def write_angle(self, degrees=None):
    degrees = degrees % 360
    total_range = self.max_us - self.min_us
    us = self.min_us + total_range * degrees // self.angle
    self.write_us(us)

while True:
  Servo(pin0).write_angle(0)
  sleep(2000)
  Servo(pin0).write_angle(90)
  sleep(2000)
  Servo(pin0).write_angle(180)
  sleep(2000)

Step Two:  Add the Block Code

Once the python code above has been added, it seems like the Block code works without an issue.  Without the above code, it doesn’t seem to work.  Now it works likes a charm.  You only seem to need to do this once per working session.  That is, if you make a change to your program, you don’t need to add the python again.

Leave a Reply

Your email address will not be published. Required fields are marked *