此扩展板上自带二电机驱动(须在扩展板上接电源),且不占用IO脚,只要把电机接上就能用了。
Code: Select all
from microbit import *
M1 = 0
M2 = 1
ALL = 2
CW = 0
CCW = 1
class IOBOX_Motor():
def __init__(self):
i2c.init()
self.buf = bytearray(3)
self.speed = 0
def motorRun(self, index, direction=CW, speed=255):
self.speed = speed
if self.speed < 0:
self.speed = 0
elif self.speed > 255:
self.speed = 255
if index > 3 or index < 0:
return
if index == M1:
self.buf[0] = 0x00
elif index == M2:
self.buf[0] = 0x02
elif index == ALL:
self.motorRun(M1, direction, self.speed)
self.motorRun(M2, direction, self.speed)
self.buf[1] = direction
self.buf[2] = self.speed
i2c.write(0x10, self.buf)
def motorStop(self, index=ALL):
self.motorRun(index, CW, 0)
if __name__ == "__main__":
mt = IOBOX_Motor()
mt.motorRun(ALL, CW, 200)
sleep(2000)
mt.motorStop()
sleep(3000)
mt.motorRun(M2, CCW, 50)
sleep(2000)
mt.motorStop()