码迷,mamicode.com
首页 > 编程语言 > 详细

利用树莓派控制步进电机——Python语言

时间:2015-01-26 15:09:05      阅读:1335      评论:0      收藏:0      [点我收藏+]

标签:raspberry pi   树莓派   步进电机   rpi.gpio   

步进电机的优点在于它能够被精确定位,正向或反向一次性转动“一步”,并且也能够连续转动。


#!/usr/bin/env python
#########################################################
#	File name: stepMotor.py
#	   Author: Jason Dai
#	     Date: 2015/01/26
#########################################################
import RPi.GPIO as GPIO
import time

IN1 = 11    # pin11
IN2 = 12
IN3 = 13
IN4 = 15

def setStep(w1, w2, w3, w4):
	GPIO.output(IN1, w1)
	GPIO.output(IN2, w2)
	GPIO.output(IN3, w3)
	GPIO.output(IN4, w4)

def stop():
	setStep(0, 0, 0, 0)

def forward(delay, steps):  
	for i in range(0, steps):
		setStep(1, 0, 0, 0)
		time.sleep(delay)
		setStep(0, 1, 0, 0)
		time.sleep(delay)
		setStep(0, 0, 1, 0)
		time.sleep(delay)
		setStep(0, 0, 0, 1)
		time.sleep(delay)

def backward(delay, steps):  
	for i in range(0, steps):
		setStep(0, 0, 0, 1)
		time.sleep(delay)
		setStep(0, 0, 1, 0)
		time.sleep(delay)
		setStep(0, 1, 0, 0)
		time.sleep(delay)
		setStep(1, 0, 0, 0)
		time.sleep(delay)

def setup():
	GPIO.setwarnings(False)
	GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
	GPIO.setup(IN1, GPIO.OUT)      # Set pin's mode is output
	GPIO.setup(IN2, GPIO.OUT)
	GPIO.setup(IN3, GPIO.OUT)
	GPIO.setup(IN4, GPIO.OUT)

def loop():
	while True:
		print "backward..."
		backward(0.003, 512)  # 512 steps --- 360 angle
		
		print "stop..."
		stop()                 # stop
		time.sleep(3)          # sleep 3s
		
		print "forward..."
		forward(0.005, 512)
		
		print "stop..."
		stop()
		time.sleep(3)

def destroy():
	GPIO.cleanup()             # Release resource

if __name__ == '__main__':     # Program start from here
	setup()
	try:
		loop()
	except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
		destroy()

运行程序:

python stepMotor.py




利用树莓派控制步进电机——Python语言

标签:raspberry pi   树莓派   步进电机   rpi.gpio   

原文地址:http://blog.csdn.net/jcdjx/article/details/43152337

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!