MicroPython Motor_Control

The motors can be controlled by the PWM controller. The drive(PWM0, PWM1, PWM2, PWM3) function takes four values between 0 and 255. This defines the motor speed. PWM0 and PWM1 define the left motor and control the forward and reverse movement. PWM2 and PWM3 define the right motor accordingly.

The additional function stop() sets all motor movements to 0 and thus performs a braking manoeuvre.

# Import of the micro:bit module
from microbit import *

# Initialization of the I2C interface
i2c.init(freq = 400000, sda = pin20, scl = pin19)

# Initialisierung des PWM Controllers
i2c.write(0x70, b'\x00\x01')
i2c.write(0x70, b'\xE8\xAA')

# Control motors using the PWM controller
# PWM0 and PWM1 for the left and PWM2 and PWM3 for the right motor
def drive(PWM0, PWM1, PWM2, PWM3):
    i2c.write(0x70, b'\x02' + bytes([PWM0])) # Transfer value for PWM channel (0-255) to PWM controller. 0x70 is the I2C address of the controller. b'\x02 is the byte for PWM channel 1. To the byte for the channel the byte with the PWM value is added.
    i2c.write(0x70, b'\x03' + bytes([PWM1])) # Repeat the process for all 4 channels
    i2c.write(0x70, b'\x04' + bytes([PWM2]))
    i2c.write(0x70, b'\x05' + bytes([PWM3]))

# stop all motors
def stop():
    drive(0, 0, 0, 0)


# Variables for the Demo-while-Loop
speed = 35
direction = "f"

# Demo-Loop
while True:

    # move forward
    if direction == "f":
        speed += 1
        drive(speed, 0, speed, 0)
        sleep(30)
        if speed > 254:
            stop()
            print("rückwärts")
            sleep(1000)
            speed = 35
            direction = "b"

    # move backwards
    elif direction == "b":
        speed += 1
        drive(0, speed, 0, speed)
        sleep(30)
        if speed > 254:
            stop()
            print("links")
            sleep(1000)
            speed = 35
            direction = "l"

    # move left
    elif direction == "l":
        speed += 1
        drive(0, speed, speed, 0)
        sleep(30)
        if speed > 254:
            stop()
            print("rechts")
            sleep(1000)
            speed = 35
            direction = "r"

    # move right
    elif direction == "r":
        speed += 1
        drive(speed, 0, 0, speed)
        sleep(30)
        if speed > 254:
            stop()
            print("vorwärts")
            sleep(1000)
            speed = 35
            direction = "f"

    # else stop
    else:
        stop()
        print("stopped")

Achtung!

Ihr Webbrowser ist veraltet. Wechseln Sie jetzt zu einem aktuellen Browser für mehr Sicherheit, Geschwindigkeit und den besten Komfort auf dieser Seite.