raspberry pi python gpio 定时器

raspberry pi python gpio timer

嗨,我正在学习 python 在 raspberry pi 3 模型 B 上编写代码,并尝试使用 GPIO。 我的脚本使 LED 在接收输入 ==1 时打开,在输入时关闭!=1。 我还想记录 LED 亮起和熄灭的时间。 (开始时间和结束时间)。 我最终使用了多个 if/elif 条件,但我确信有更好的方法可以做到这一点。请赐教!

import RPi.GPIO as GPIO
import time
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(7,GPIO.OUT)
GPIO.output(7,0) #set ping 7 to be 0 at default
CatchTime = True
startTime = []
startTimeRead = []
endTime = []
try:
        while True:
                time.sleep(0.25)
                if (GPIO.input(11) ==1)and CatchTime==True :  #start counting
                        GPIO.output(7,1)
                        print(time.ctime())
                        startTime.append(time.time())
                        startTimeRead.append(time.ctime())
                        CatchTime = False
                elif (GPIO.input(11) ==1)and CatchTime != True : #within count
                        GPIO.output(7,1)
                        print(time.ctime())
                elif (GPIO.input(11) !=1) and CatchTime != True : #end of count
                        GPIO.output(7,0)
                        CatchTime = True
                        endTime.append(time.time())
                else:   #steady not count
                        GPIO.output(7,0)
                        CatchTime = True

except KeyboardInterrupt:
    GPIO.cleanup()


print('start time:',startTimeRead)
print('end time:',endTime)

通常,更好的方法是为上升和下降事件创建中断函数。你现在正在做的是关于如何使用 gpio 中断的 busy waiting while polling for an input. Interrupts are generally cleaner and more reliable. Computerphile has a nice overview on interrupts in general (more from the computer aspect of things), and a quick google search found this 教程 rasberry-pi。

我建议查看 Raspberry Pi SO 上的 this post (Raspberry Pi- GPIO Events in Python)。该解决方案展示了如何使用事件,因此您不必 运行 一个恒定的循环 - 它只会在有变化时通知您。