gpt4 book ai didi

python - 树莓派 GPIO 定时器

转载 作者:太空宇宙 更新时间:2023-11-03 15:46:25 25 4
gpt4 key购买 nike

嗨,我正在学习在树莓派 3 B 型上编写 Python 代码,并使用 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)

最佳答案

通常,更好的方法是为上升和下降事件创建中断函数。您现在正在做的事情被称为busy waitingpolling用于输入。中断通常更干净、更可靠。 Computerphile对一般中断有一个很好的概述(更多来自计算机方面的事物),并且快速谷歌搜索发现this有关如何通过 rasberry-pi 使用 GPIO 中断的教程。

关于python - 树莓派 GPIO 定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41702439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com