PIR Sensor + LED || Is this code well implemented?

All ESP32 boards running MicroPython.
Target audience: MicroPython users with an ESP32 board.
Post Reply
klindber
Posts: 4
Joined: Sun Jun 09, 2019 5:37 pm
Location: Madrid, España

PIR Sensor + LED || Is this code well implemented?

Post by klindber » Sat Jun 29, 2019 4:49 pm

Hello!
I made this testing of a PIR Sensor (movement) that just turns a LED on, using ISR's.

I just want to share it with you and ask if this interrupt is well implemented, and else how can it be improved.

Code: Select all

from machine import Pin
from time import sleep

motion = False

def handle_interrupt(pin):  #Avoid using print() inside isr
  global motion
  motion = True
  global int_pin
  int_pin = pin
  
led = Pin(4, Pin.OUT)
pir = Pin(14, Pin.IN)

pir.irq(trigger = Pin.IRQ_RISING, handler = handle_interrupt)

while True:
  if motion:
    print('Motion detected! Interrupt on pin:', int_pin)
    led.on()
    sleep(5)
    led.off()
    print('Motion stopped')
    motion = False
Thanks for any help!

-klindber

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: PIR Sensor + LED || Is this code well implemented?

Post by dhylands » Sat Jun 29, 2019 9:30 pm

You may want to use micropython.schedule, then you don't need to poll in your main code.

See: https://docs.micropython.org/en/latest/ ... n-schedule (and the rest of the page is all about writing ISRs)

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: PIR Sensor + LED || Is this code well implemented?

Post by pythoncoder » Sun Jun 30, 2019 7:25 am

If your aim is to understand interrupts then your approach is fine (although I agree with the comment of @dhylands).

But in terms of the actual application the interrupt isn't adding any functionality that wouldn't be available by polling the pin. Something along these lines is simpler and should work equally well.

Code: Select all

from machine import Pin
from time import sleep

led = Pin(4, Pin.OUT)
pir = Pin(14, Pin.IN)

while True:
  if pir():
    print('Motion detected!')
    led.on()
    sleep(5)
    led.off()
    if not pir():
        print('Motion stopped')
Learning exercises aside, it's best to use interrupts only when there is a real need for them.
Peter Hinch
Index to my micropython libraries.

Post Reply