2016-05-19 51 views
0

我正在做一個項目,我需要移動兩臺電機,它們有不同的運動。有代碼:以不同速度移動直流電機

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

嚴重的是,使用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 
相關問題