ESP32 Deepsleep with external input trigger

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
kma_jg
Posts: 3
Joined: Sun Oct 28, 2018 11:49 pm

ESP32 Deepsleep with external input trigger

Post by kma_jg » Mon May 06, 2019 10:47 am

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

Online
User avatar
jimmo
Posts: 421
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia

Re: ESP32 Deepsleep with external input trigger

Post by jimmo » Mon May 06, 2019 11:41 am

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.

Post Reply