reading PIR sensor/pin via interrupt

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
fluxmonkey
Posts: 1
Joined: Wed Jan 19, 2022 3:47 am

reading PIR sensor/pin via interrupt

Post by fluxmonkey » Wed Jan 19, 2022 4:20 am

TW: TOTAL NOOB question. I'm working through "Getting Started with Micropython on Raspberry Pi Pico", there's a Burglar Alarm project using the HC-SR501 PIR sensor. The example code works:

Code: Select all

import machine
import utime

sensor_pir = machine.Pin(28, machine.Pin.IN, machine.Pin.PULL_DOWN)
 
def pir_handler(pin):
    utime.sleep_ms(100)
    if pin.value():
        print("Danger Will Robinson!!!")
                      
sensor_pir.irq(trigger=machine.Pin.IRQ_RISING, handler=pir_handler)
and prints out the message whenever the PIR is triggered. What I want to do is print one message on trigger, and then another when the PIR untriggers (pin28 returns to low). I tried this:

Code: Select all

def pir_handler(pin):
    utime.sleep_ms(100)
    if pin.value()==1:
        print("Danger Will Robinson!!!")
    elif pin.value()==0:
        print("coast is clear")
   
sensor_pir.irq(trigger=machine.Pin.IRQ_RISING, handler=pir_handler)
and multiple other permutations of if and elif; I still get the Danger message but never the clear. I may not understand, in the textbook example, what exactly that if is evaluating... is that "if pin.value is not empty", or?
I also tried adding second .irq with an IRQ_FALLING condition, but by then I was just randomly flailing and not getting anywhere. Thanks in advance for your help!

iiLaw
Posts: 5
Joined: Sun Jan 23, 2022 10:04 am

Re: reading PIR sensor/pin via interrupt

Post by iiLaw » Sun Jan 23, 2022 9:07 pm

Hi have you played with utime.sleep_ms(100) which looks to me as denounce so you could lengthen it as PIR can be very noisy in terms of triggering. Is the PIR on a module as some have back off timer of 5 sec to stop re-triggering.
The other thing is to put a pin read in a loop and print state as that might help showing what's going on.
You will need something like time.ticks_us() I'm new to micropython so can't say how to use but a google should help

I found this thread
viewtopic.php?t=4641#p26839

Post Reply