servo.py
The hobby servo follows a potentiometer read on analog pin0: the 20 ms period and 500-2500 µs pulse are generated natively by MicroPython. Pressing A forces 90°, and the angle shows on the matrix.
Required hardware
A BBC micro:bit V2 (nRF52833, 5×5 LED matrix, A/B buttons, accelerometer + compass, microphone and speaker) powered over USB or a battery pack. 1 SG90 servo + 1 10 kΩ potentiometer; external 5 V supply advised for the servo.
Wiring
Potentiometer: wiper to pin0, ends to 3V3 and GND. Servo: signal to pin1, + to external 5 V, common grounds.
How it works
read_analog() returns 0-1023 scaled to 0-180°; set_analog_pulse_us applies the standard pulse. The 3° deadband stops servo jitter around the value.
Running it
Open python.microbit.org, paste the MicroPython program and send it to the board (the micro:bit shows up as a MICROBIT drive). Press reset to restart.
Variants
Replace the potentiometer with tilt (accelerometer.get_x) for a part-free arm, or store positions on long press.
servo.py
# Servo d'angle sur pin1 : angle suivi depuis l'entree analogique pin0.
from microbit import *
# MicroPython micro:bit : pulse servo via pin1.set_analog_period(20ms)
# puis set_analog_pulse_us(500..2500).
pin1.set_analog_period(20)
def angle_vers_pulse(a):
# 0 degre = 500 us ; 180 degres = 2500 us (standard servo).
return 500 + int(a * 2000 / 180)
dernier_angle = -1
while True:
brut = pin0.read_analog() # 0..1023 (potentiometre)
angle = brut * 180 // 1023
if abs(angle - dernier_angle) > 3: # filtre anti-bruit
dernier_angle = angle
pin1.set_analog_pulse_us(angle_vers_pulse(angle))
display.show(str(angle))
# Bouton A : position 90 degres ; bouton B : balayage auto.
if button_a.was_pressed():
pin1.set_analog_pulse_us(angle_vers_pulse(90))
display.show(Image.TARGET)
sleep(20)
# Potentiometre : curseur sur pin0, 3V3 d'un cote, GND de l'autre.
# Servo : signal sur pin1, VCC externe 5V, GND commun.