嗨,我正在学习在raspberry pi 3模型B上编写python代码并使用GPIO。 我的脚本在接收输入== 1时打开LED,在输入时关闭!= 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)
答案 0 :(得分:1)
通常,更好的方法是为上升和下降事件创建中断函数。你正在做的事情被称为busy waiting而polling被称为输入。中断通常更清洁,更可靠。 Computerphile对中断有一个很好的概述(更多来自计算机方面的事情),并且快速谷歌搜索找到this教程,了解如何使用rasberry-pi进行gpio中断。
答案 1 :(得分:0)
我建议在Raspberry Pi SO上查看this post (Raspberry Pi- GPIO Events in Python)。该解决方案显示了如何使用事件,因此您不必运行常量循环 - 只会在发生更改时通知您。