以不同的速度移动直流电机

时间:2016-05-19 21:34:19

标签: python raspberry-pi

我做了一个项目,我需要移动两台电机,它们有不同的动作。有代码:

import RPi.GPIO as GPIO ## Import GPIO library
import time ## Import 'time' library. Allows us to use 'sleep'
import sys

GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
GPIO.setup(19, GPIO.OUT) ## Setup GPIO Pin 11(motor b enable) to OUT
GPIO.setup(16, GPIO.OUT)  ## Setup GPIO Pin 11(motor a enable) to OUT
GPIO.setup(22, GPIO.OUT) ## Setup GPIO Pin 11(motor a control) to OUT
GPIO.setup(18, GPIO.OUT)  ## Setup GPIO Pin 11(motor a control) to OUT
GPIO.setup(23, GPIO.OUT)   ## Setup GPIO Pin 11(motor b control) to OUT
GPIO.setup(21, GPIO.OUT)    ## Setup GPIO Pin 11(motor b control) to OUT
GPIO.output(16, False)        ## disable motor a
GPIO.output(19, True)          ## enable motor b
p=GPIO.PWM(19,50)          ## frequency 50
p.start(1)
try:
    while True:
           GPIO.output(22, False)   ## dont run motor a
           GPIO.output(18, False)      ## dont run motor a
           GPIO.output(23, True)        ##  run motor b
           GPIO.output(21, False)         ##  run motor b
           p.ChangeDutyCycle(35)     ## duty cycle 10%
except KeyboardInterrupt:
     pass
p.stop()
GPIO.cleanup()
sys.exit()

代码#2

import RPi.GPIO as GPIO
from time import sleep
import sys

GPIO.setmode(GPIO.BOARD)

Motor1A = 22
Motor1B = 18
Motor1E = 16

Motor2A = 23
Motor2B = 21
Motor2E = 19

GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1E,GPIO.OUT)

GPIO.setup(Motor2A,GPIO.OUT)
GPIO.setup(Motor2B,GPIO.OUT)
GPIO.setup(Motor2E,GPIO.OUT)

print "Going forwards"
GPIO.output(Motor1A,GPIO.HIGH)
GPIO.output(Motor1B,GPIO.LOW)
GPIO.output(Motor1E,GPIO.HIGH)

GPIO.output(Motor2A,GPIO.HIGH)
GPIO.output(Motor2B,GPIO.LOW)
GPIO.output(Motor2E,GPIO.HIGH)

sleep(2)




print "Now stop"
GPIO.output(Motor1E,GPIO.LOW)
GPIO.output(Motor2E,GPIO.LOW)

GPIO.cleanup()
sys.exit()

我想将两个代码混合在一起。我的意思是,将这两个代码转换为具有两个不同速度的代码。

或者如果有人知道另一个代码,我会非常感激

我该怎么做?

1 个答案:

答案 0 :(得分:1)

说真的,使用gpiozero,它会更有趣并将您的代码转换为:

from gpiozero import Motor
from time import sleep

motorA = Motor(22, 18)  # your gpio pins go here
motorB = Motor(23, 21)

motorA.forward(0.5)  # half speed
motorB.forward(0.5)
sleep(2)  # wait 2 seconds before stopping the motors
motorA.stop()
motorB.stop()

然后,您可以更进一步,使用Robot课程(文档here),让一切变得更加轻松:

from gpiozero import Robot
from time import sleep

robot = Robot(left=(22, 18), right=(23, 21))

robot.forward(1)  # full speed
sleep(2)
robot.stop()

机器人类还有一些功能,例如:

robot.left()
robot.right()

最有可能的是,如果您尚未使用该库,则必须先安装该库。在终端上键入以下内容以进行此操作。

pip install gpiozero