我有一个连接到树莓派的线性执行器,通过按钮按下打开和关闭。我希望那个执行器移动一段规定的时间。示例:我希望执行器运行的总时间为5秒。如果用户按下按钮以启动执行器,则它开始移动。然后在3秒后用户再次按下按钮停止。然后,如果他们再次推动它,它会开始移动,并在5秒后自动停止。这是我用按钮运行电机的代码,我只是想现在整合时序。有什么想法吗?
from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor
import RPi.GPIO as GPIO
import atexit
from time import sleep
from threading import Thread
GPIO.setmode(GPIO.BCM)
GPIO.setup(23,GPIO.IN)
GPIO.setup(24,GPIO.IN)
# create a default object, no changes to I2C address or frequency
mh = Adafruit_MotorHAT(addr=0x60)
# recommended for auto-disabling motors on shutdown!
def turnOffMotors():
mh.getMotor(1).run(Adafruit_MotorHAT.RELEASE)
mh.getMotor(2).run(Adafruit_MotorHAT.RELEASE)
mh.getMotor(3).run(Adafruit_MotorHAT.RELEASE)
mh.getMotor(4).run(Adafruit_MotorHAT.RELEASE)
atexit.register(turnOffMotors)
################################# DC motor test!
myMotor = mh.getMotor(3)
# set the speed to start, from 0 (off) to 255 (max speed)
myMotor.setSpeed(255)
myMotor.run(Adafruit_MotorHAT.FORWARD);
# turn on motor
myMotor.run(Adafruit_MotorHAT.RELEASE);
snooziness = 5
stateOn = 0
stateOff = 0
while (True):
if(GPIO.input(23)== False) and (stateOn==0):
myMotor.run(Adafruit_MotorHAT.FORWARD)
sleep(snooziness)
myMotor.run(Adafruit_MotorHAT.RELEASE)
stateOn=1
if(GPIO.input(23)== False) and (stateOn==1):
myMotor.run(Adafruit_MotorHAT.RELEASE)
stateOn=0
if(GPIO.input(24)== False) and (stateOff==0):
myMotor.run(Adafruit_MotorHAT.BACKWARD)
sleep(snooziness)
myMotor.run(Adafruit_MotorHAT.RELEASE)
stateOff=1
if(GPIO.input(24)== False) and (stateOff==1):
myMotor.run(Adafruit_MotorHAT.RELEASE)
stateOn=0
continue
答案 0 :(得分:0)
可能是这样的:
import time
running = False
stop_time = None
while(True):
if(buttonPushed()):
if running:
running = False
stop_motor()
stop_time = None
else
running = True
start_motor()
stop_time = time.time() + 5
if stop_time is not None and time.time() > stop_time():
running = False
stop_motor()
stop_time = None
我认为这证明了我使用的逻辑,尽管那里显然有一些可以整理的代码冗余