因为端口的限制,microbit最多只支持两三个步进电机同时转动
注意:同时转动,不是交替转动,弥补microbit不支持多线程的缺陷
Code: Select all
from microbit import *
# 关闭microbit的显示器,以释放被其占用的引脚
display.off()
# 转一圈需要509步多一点
FULL_ROTATION = 509
# 全步励磁
HALF_STEP = [
[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 0, 1, 0],
[0, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 0],
[1, 0, 0, 0],
[1, 0, 0, 1],
]
# 半步励磁
FULL_STEP = [
[1, 0, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 0],
[1, 1, 0, 0]
]
class MultiStepper():
def __init__(self):
self.servoList = []
def addServo(self, pin_1, pin_2, pin_3, pin_4):
self.servoList.append([pin_1, pin_2, pin_3, pin_4])
# servoIndexList--电机索引列表,第一个添加的电机索引为0
# directionList --电机转动方向列表 1表示逆时候,-1表示顺时针
def doAction(self, servoIndexList, directionList, stepCount, mode=FULL_STEP, delay=5):
for x in range(stepCount):
for y in range(len(mode)):
for z in range(len(servoIndexList)):
pinList = self.servoList[servoIndexList[z]]
bit = mode[::directionList[z]][y]
pinList[0].write_digital(bit[0])
pinList[1].write_digital(bit[1])
pinList[2].write_digital(bit[2])
pinList[3].write_digital(bit[3])
sleep(delay)
for i in range(len(servoIndexList)):
pinList = self.servoList[servoIndexList[i]]
pinList[0].write_digital(0)
pinList[1].write_digital(0)
pinList[2].write_digital(0)
pinList[3].write_digital(0)
if __name__ == '__main__':
s = MultiStepper()
# 添加第一个电机
s.addServo(pin16, pin15, pin14, pin13)
# 添加第二个电机
s.addServo(pin8, pin2, pin1, pin0)
# 第一个电机顺时针走255步,全步励磁
s.doAction([0],[-1],255, FULL_STEP)
# 第一个电机逆时针和第二个电机顺时针各转一圈,半步励磁
s.doAction([0, 1], [1, -1], FULL_ROTATION, HALF_STEP, 5)
# 第二个电机逆时针走255步,全步励磁
s.doAction([1],[1],255, FULL_STEP)[/i]