掌控板IO扩展板——板载电机驱动

micro:bit编程、教学、展示
STEM
回复
头像
shaoziyang
帖子: 3917
注册时间: 2019年 10月 21日 13:48

掌控板IO扩展板——板载电机驱动

#1

帖子 shaoziyang »

原帖作者:chpczx 发表于 2019-7-9 

此扩展板上自带二电机驱动(须在扩展板上接电源),且不占用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()

回复

  • 随机主题
    回复总数
    阅读次数
    最新文章