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 Stepper():
def __init__(self, mode, pin_1, pin_2, pin_3, pin_4, delay=5):
self.mode = mode
self.pin_1 = pin_1
self.pin_2 = pin_2
self.pin_3 = pin_3
self.pin_4 = pin_4
self.delay = delay
self.reset()
def step(self, stepCount, direction=1):
""" direction = -1 时顺时针转动"""
for x in range(stepCount):
for bit in self.mode[::direction]:
self.pin_1.write_digital(bit[0])
self.pin_2.write_digital(bit[1])
self.pin_3.write_digital(bit[2])
self.pin_4.write_digital(bit[3])
sleep(self.delay)
self.reset()
def reset(self):
self.pin_1.write_digital(0)
self.pin_2.write_digital(0)
self.pin_3.write_digital(0)
self.pin_4.write_digital(0)
if __name__ == '__main__':
s1 = Stepper(FULL_STEP, pin16, pin15, pin14, pin13, delay=5)
for i in range(3):
s1.step(FULL_ROTATION/2)
s1.step(509/2,-1)