步进电机驱动实验

步进电机驱动实验

#实验目的:通过树莓派、ULN2003驱动板以及步进电机,实现转动指定步数,以及反向转动等效果。
#接线效果如图:
接线示例
#关键代码:
代码示例

#!/usr/bin/env python
#coding:utf-8

'''
from JiuJiang
树莓酱的操作实例
http:://www.shumeijiang.com
'''

import RPi.GPIO as GPIO ##引入GPIO模块
import time    ##引入time库

#定义四个引脚
IN1Pin = 18
IN2Pin = 19
IN3Pin = 20
IN4Pin = 21

#设置为BCM编码 同时四个引脚为输出模式
GPIO.setmode(GPIO.BCM)
GPIO.setup(IN1Pin, GPIO.OUT)
GPIO.setup(IN2Pin, GPIO.OUT)
GPIO.setup(IN3Pin, GPIO.OUT)
GPIO.setup(IN4Pin, GPIO.OUT)

#定义初始化
def setVal(val1, val2, val3, val4):
    GPIO.output(IN1Pin, val1)
    GPIO.output(IN2Pin, val2)
    GPIO.output(IN3Pin, val3)
    GPIO.output(IN4Pin, val4)

#初始化四个引脚
setVal(GPIO.LOW, GPIO.LOW, GPIO.LOW, GPIO.LOW)

#定义一步需要的操作
def oneStep(dely):
    if not dely:
        dely = 0.005
    setVal(GPIO.HIGH, GPIO.LOW, GPIO.LOW, GPIO.LOW)
    time.sleep(dely)
    setVal(GPIO.LOW, GPIO.HIGH, GPIO.LOW, GPIO.LOW)
    time.sleep(dely)
    setVal(GPIO.LOW, GPIO.LOW, GPIO.HIGH, GPIO.LOW)
    time.sleep(dely)
    setVal(GPIO.LOW, GPIO.LOW, GPIO.LOW, GPIO.HIGH)
    time.sleep(dely)

#定义一步(反向)需要的操作
def oneStepBack(dely):
    if not dely:
        dely = 0.005
    setVal(GPIO.LOW, GPIO.LOW, GPIO.LOW, GPIO.HIGH)
    time.sleep(dely)
    setVal(GPIO.LOW, GPIO.LOW, GPIO.HIGH, GPIO.LOW)
    time.sleep(dely)
    setVal(GPIO.LOW, GPIO.HIGH, GPIO.LOW, GPIO.LOW)
    time.sleep(dely)
    setVal(GPIO.HIGH, GPIO.LOW, GPIO.LOW, GPIO.LOW)
    time.sleep(dely)

#定义多步操作
def walk(steps, direction):
    if not steps:
        return ;
    if not direction:
        direction = 'forward'

    for i in range(0, steps):
        if direction == 'backward':
            oneStepBack(0.005)
        else:
            oneStep(0.005)

        time.sleep(0.01)  ##每步间的间隔

#执行步进
try:
    steps = input('前进多少步?')
    walk(steps, 'forward')  ##正向走对应步数
    walk(steps, 'backward') ##反向走对应的步数

except KeyboardInterrupt:
    pass

GPIO.cleanup()
#实验效果:
1、执行代码 Python jiujiang.py;
2、可见提示需要输入要走的步数;
3、输入100步后,可见步进电机持续转动;
4、正向转动结束后,会立即反向再转动100步,到达期初的位置;
5、具体转动规则可自定义。
#视频效果如下:
jiujiang

评论已关闭。