<p><strong>RPi.GPIO</strong>Python库现在支持<strong>Events</strong>,这在<a href="https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/" rel="noreferrer">Interrupts and Edge detection</a>段中有解释。</p>
<p>因此,使用<code>sudo rpi-update</code>更新覆盆子Pi以获取库的最新版本后,可以将代码更改为:</p>
<pre><code>from time import sleep
import RPi.GPIO as GPIO
var=1
counter = 0
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def my_callback(channel):
if var == 1:
sleep(1.5) # confirm the movement by waiting 1.5 sec
if GPIO.input(7): # and check again the input
print("Movement!")
captureImage()
# stop detection for 20 sec
GPIO.remove_event_detect(7)
sleep(20)
GPIO.add_event_detect(7, GPIO.RISING, callback=my_callback, bouncetime=300)
GPIO.add_event_detect(7, GPIO.RISING, callback=my_callback, bouncetime=300)
# you can continue doing other stuff here
while True:
pass
</code></pre>
<p>我之所以选择<a href="https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/" rel="noreferrer">Threaded callbacks</a>方法,是因为我认为您的程序会并行执行一些其他操作来更改<code>var</code>的值。</p>