Page 1 of 1

ESP32 Deepsleep with external input trigger

Posted: Mon May 06, 2019 10:47 am
by kma_jg
Hi,
I've been searching for some examples of using a PIR and waking up the ESP32 (NodeMCU ESP32S v1.1) when the PIR detects motion, but I'm yet to find anything that works.

MicroPython v1.10-227-g696549d2e on 2019-03-17

My code is very simple and would appreciate suggestions where to put the ESP in deepsleep and wakeup when the PIR detects motion.

Code: Select all

>>> import machine as m
>>> pir = m.Pin(13, Pin.IN)
>>>
>>> def handle_interrupt(pin):
...     global motion
...     motion = True
...     global interrupt_pin
...     interrupt_pin = pin
...
...
...
>>> pir.irq(handle_interrupt,(m.Pin.IRQ_RISING))
<IRQ>
>>> while 1:
...         if motion:
...             print('Motion detected on: {}'.format(interrupt_pin))
...             sleep(10)
...             print('Motion stopped')
...             motion = False
...
...
...
Motion detected on: Pin(13)
Motion stopped
Motion detected on: Pin(13)
Motion stopped

Re: ESP32 Deepsleep with external input trigger

Posted: Mon May 06, 2019 11:41 am
by jimmo
Hi,

Sorry I don't have an ESP32 handy to check this with but the basic idea with deep sleep is that when the device wakes from sleep, it looks as though it's reset (i.e. it starts your main.py from the beginning).

So the steps are:

- Figure out why the program was reset (see machine.wake_reason -- http://docs.micropython.org/en/v1.10/li ... ake_reason). If it was due to wake-from-sleep then you know that the pin changed.
- Configure the pin to enable wake-on-change. (see the 'wake' parameter to Pin.irq -- http://docs.micropython.org/en/v1.10/li ... ne.Pin.irq) (i.e. set wake=True rather than setting a handler)
- Put the machine back to sleep (machine.deepsleep -- http://docs.micropython.org/en/v1.10/li ... .deepsleep)

You might find it easier to use `machine.sleep` instead, where instead of starting from the beginning, your program will just continue from that line.