1

I have a program for detecting motion in raspberry zero but I need to also have the capability to react when a button is pressed. But I can't. Can someone give me lights what should I do? The thing is working like this at first the pir is detecting motion, then it stops until I press the button, then I press the button and pir start to work again and I'm stuck in that bucle. I need both pir and button 'listening' at the same time My code (simplified) is working like this:

from gpiozero import MotionSensor
from gpiozero import Button
pir = MotionSensor(4)
button = Button(2)
postOnDb():
  print("Posted on db")
turnOff():
  print("Turned off")
while True:
        pir.wait_for_motion()
        postOnDB()  #Every time the sensor detect motion this method should be call
        button.wait_for_press() #At Any time this button is press program should call this method
        turnOff()

2 Answers 2

0

Your question is far too general. The real answer is to learn to program.

Forget trying to put everything in a loop; that is the road to disaster. wait_for blocks program execution and is only appropriate for single tasks.

The best course of action is probably to use callbacks, but that only works if you design your code to achieve multiple tasks - start from a top down plan, rather that trying to patch a bottom up model.

There are many examples on the gpiozero site.

The following links may provide a good starting point, but there is not a shortcut to avoid a plan. https://gpiozero.readthedocs.io/en/v1.6.2/faq.html?highlight=callback#how-do-i-use-button-when-pressed-and-button-when-held-together

0
0

There is this concept called multithreading, allocating the "same" (or multiple) CPU's for multiple tasks to be executed "at once". This may help you getting started: https://www.toptal.com/python/beginners-guide-to-concurrency-and-parallelism-in-python

It takes some learning and paradigm changing, but it is very powerful when you learn it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.