Py学习  »  Python

如何在python中添加硬件控制的定时延迟

Cody Dieckow • 4 年前 • 309 次点击  

我已经在Raspberry PI上构建了一些Python代码来控制车库门。但是,我不知道如何添加一个定时延迟,以便控制被限制在正确的移动时间内。

任何帮助都将不胜感激。

我的工作代码如下。

    import RPi.GPIO as GPIO          
    from time import sleep

    in1 = 24
    in2 = 23
    en = 25
    temp1=1

   GPIO.setmode(GPIO.BCM)
   GPIO.setup(in1,GPIO.OUT)
   GPIO.setup(in2,GPIO.OUT)
   GPIO.setup(en,GPIO.OUT)
   GPIO.output(in1,GPIO.LOW)
   GPIO.output(in2,GPIO.LOW)
   p=GPIO.PWM(en,1000)
   p.start(25)
   print("\n")
   print("The default speed & direction of motor is LOW & Forward.....")
   print("r-run s-stop f-forward b-backward l-low m-medium h-high e-exit")
   print("\n")    

   while(1):
   x = input()
   if x=='r':
   print("run")
   if(temp1==1):
   GPIO.output(in1,GPIO.HIGH)
   GPIO.output(in2,GPIO.LOW)
   print("forward")
   x='z'
   else:
   GPIO.output(in1,GPIO.LOW)
   GPIO.output(in2,GPIO.HIGH)
   print("backward")
   x='z'


   elif x=='s':
   print("stop")
   GPIO.output(in1,GPIO.LOW)
   GPIO.output(in2,GPIO.LOW)
   x='z'

   elif x=='f':
   print("forward")
   GPIO.output(in1,GPIO.HIGH)
   GPIO.output(in2,GPIO.LOW)
   temp1=1
   x='z'

   elif x=='b':
   print("backward")
   GPIO.output(in1,GPIO.LOW)
   GPIO.output(in2,GPIO.HIGH)
   temp1=0
   x='z'

   elif x=='l':
   print("low")
   p.ChangeDutyCycle(25)
   x='z'

   elif x=='m':
   print("medium")
   p.ChangeDutyCycle(50)
   x='z'

   elif x=='h':
   print("high")
   p.ChangeDutyCycle(75)
   x='z'


    elif x=='e':
    GPIO.cleanup()
    break

    else:
    print("<<<  wrong data  >>>")
    print("please enter the defined data to continue.....")
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38260
 
309 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Preet Sangha
Reply   •   1 楼
Preet Sangha    5 年前

这个问题和答案 How can I make a time delay in Python? 显示如何在代码中添加定时延迟。

import time
# delay for 10 seconds
time.sleep(10)

然而,这不是最好的解决方案。最好在这里使用解决方案: https://raspberrypi.stackexchange.com/questions/69640/add-delay-between-two-gpio-output 我还建议你用别针来捕捉诸如从门上打开或关闭之类的信息,也许可以使用传感器开关(其中有各种类型)。

Preet Sangha
Reply   •   2 楼
Preet Sangha    5 年前

无法帮助处理pi代码,但希望添加一点警告。如果你依靠时间关掉汽车,那么任何汽车、小孩、自行车等都会被关闭的门压坏。你能把一个电流传感器连接到饼图上吗?这样当电机电流超过一定量时,饼图就会停止工作。看看 These

迈克。