# Two-wheel servo car on the Kitronik Simple Servo board, MicroPython for the BBC Micro:bit.
# Open it in https://python.microbit.org and download it to the Micro:bit.
# Servo 1 (pin 8) is the LEFT wheel, Servo 2 (pin 15) is the RIGHT wheel. Both are 360° servos.
# Button A: drive forward for 2 seconds. Button B: spin right for 1 second.
from microbit import *

LEFT_SERVO = pin8
RIGHT_SERVO = pin15

for servo in (LEFT_SERVO, RIGHT_SERVO):
    servo.set_analog_period(20)        # servos want a pulse every 20 ms


def set_wheel(servo, speed):
    """speed from -100 (full backward) to 100 (full forward), 0 = stand still."""
    if servo is RIGHT_SERVO:
        speed = -speed                 # the right servo faces the other way
    pulse_microseconds = 1500 + speed * 8   # 1500 = stand still, 700 and 2300 = full speed
    servo.write_analog(round(pulse_microseconds * 1024 / 20000))


def drive(left_speed, right_speed):
    set_wheel(LEFT_SERVO, left_speed)
    set_wheel(RIGHT_SERVO, right_speed)


def stop_car():
    LEFT_SERVO.write_digital(0)        # no pulses: the servos stop and rest
    RIGHT_SERVO.write_digital(0)


while True:
    if button_a.was_pressed():
        display.show(Image.ARROW_N)
        drive(50, 50)                  # both wheels forward: straight ahead
        sleep(2000)
        stop_car()
        display.clear()
    if button_b.was_pressed():
        display.show(Image.ARROW_E)
        drive(50, -50)                 # left forward, right backward: spin right
        sleep(1000)
        stop_car()
        display.clear()
    sleep(20)
