Raspberry Pi-Python 中的 GPIO 事件 [英] Raspberry Pi- GPIO Events in Python

查看:36
本文介绍了Raspberry Pi-Python 中的 GPIO 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Raspberry Pi 上的 GPIO 引脚和 PIR 传感器来检测运动.当传感器检测到运动时,我想将软件移动到其他功能上.

I am using the GPIO pins on my Raspberry Pi with a PIR sensor to detect motion. When the sensor detects motion I want to then move the software onto other functions.

目前,为了检测运动,我让我的程序在等待检测运动时不断循环运行.虽然这目前有效,但在未来使用时,这将非常低效,我希望通过将其分配给事件来改进这一点.

At the moment, to detect motion I have my program constantly running in a loop while it is waiting for motion to be detected. While this works at the moment, for use in the future this will be incredibly inefficient and am hoping to improve on this by assigning it to an event.

有什么方法可以将我的 GPIO 输入绑定到程序检测到的事件,而无需手动运行循环.

Is there any way to bind my GPIO input to an event that is detected by the program without manually running a loop.

这是我当前检测运动的循环:

Here is my current loop for detection motion:

var = 1
counter = 0
while var == 1:
    if GPIO.input(7):
        counter += 1
        time.sleep(0.5)
    else:
        counter = 0
        time.sleep(1)

    if counter >= 3:
        print "Movement!"
        captureImage()
        time.sleep(20)

计数器和多次检测运动用于减少传感器拾取的误报数量.

The counter and detecting motion multiple times is used to reduce the number of false positives that the sensor picks up.

推荐答案

RPi.GPIO Python 库现在支持 事件,在 中断和边缘检测段落.

The RPi.GPIO Python library now supports Events, which are explained in the Interrupts and Edge detection paragraph.

因此,在使用 sudo rpi-update 更新您的 Raspberry Pi 以获取最新版本的库后,您可以将代码更改为:

So after updating your Raspberry Pi with sudo rpi-update to get the latest version of the library, you can change your code to:

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

我选择了 线程回调 方法,因为我认为您的程序并行执行一些其他操作以更改 var 的值.

I chose the Threaded callbacks method because I suppose that your program does some other things in parallel to change the value of var.

这篇关于Raspberry Pi-Python 中的 GPIO 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆