一、目的
这一节我们来学习如何使用合宙ESP32 C3连接ULN2003达林顿28BYJ48步进电机,实现步进电机指定角度旋转。下面我们一起来学习一下吧!
在很早之前我们也学习过步进电机,先让我们温习一下:
二、环境
ESP32 C3开发板(MicroPython v1.19.1 on 2022-06-18)+ ULN2003达林顿28BYJ48步进电机机 + 几根杜邦线 + Win10商业版
ESP32 C3和各模块接线方法:
三、ULN2003驱动
uln2003.py
from machine import Pin
import time
# only test for uln2003
class ULN2003:
FULL_ROTATION = int(4075.7728395061727 / 8)
"""Four phase eight beat timing"""
HALF_STEP = [
[0, 1, 1, 1],
[0, 0, 1, 1],
[1, 0, 1, 1],
[1, 0, 0, 1],
[1, 1, 0, 1],
[1, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 1, 0],
]
"""Four phase double four beat timing"""
FULL_STEP = [
[0, 1, 1, 0],
[0, 0, 1, 1],
[1, 0, 1, 1],
[1, 1, 0, 0]
]
def __init__(self, mode, pin1, pin2, pin3, pin4, delay):
if mode=='FULL_STEP':
self.mode = self.FULL_STEP
else:
self.mode = self.HALF_STEP
self.pin1 = pin1
self.pin2 = pin2
self.pin3 = pin3
self.pin4 = pin4
self.delay = delay # Recommend 10+ for FULL_STEP, 1 is OK for HALF_STEP
# Initialize all to 0
self.reset()
def step(self, count, direction = 1):
"""Rotate count steps. direction = -1 means backwards"""
if count<0:
direction = -1
count = -count
for x in range(count):
for bit in self.mode[::direction]:
self.pin1(bit[0])
self.pin2(bit[1])
self.pin3(bit[2])
self.pin4(bit[3])
time.sleep_ms(self.delay)
self.reset()
def angle(self, r, direction=1):
self.step(int(self.FULL_ROTATION * r / 360), direction)
def reset(self):
# Reset to 0, no holding, these are geared, you can't move them
self.pin1(0)
self.pin2(0)
self.pin3(0)
self.pin4(0)
四、示例程序
demo.py
from machine import Pin
from uln2003 import ULN2003 # 导入驱动
# motor1使用八拍模式
motor1 = ULN2003(ULN2003.HALF_STEP,Pin(2,Pin.OUT),Pin(3,Pin.OUT),Pin(10,Pin.OUT),Pin(6,Pin.OUT),delay = 2)
# motor2使用四拍模式
motor2 = ULN2003(ULN2003.FULL_STEP,Pin(2,Pin.OUT),Pin(3,Pin.OUT),Pin(10,Pin.OUT),Pin(6,Pin.OUT),delay = 2)
def Motor():
# 八拍减速比是64, 64 * 8 = 512步,对应的是360度。
# 64 * 8 = 512 = 360
# 步数
motor1.step(512/2, 1) # 180度,正转
motor1.step(512,-1) # 180度,反转
# (360度数 / 5.625步间距) * 64 = 4096 个脉冲
# 角度
motor2.angle(180,1)
motor2.angle(360,-1)
def main():
while True:
Motor()
if __name__ == "__main__":
main()
演示效果:
五、步进电机简介
六、步进电机模块购买
1,步进电机购买地址: