RTC wakeup callback should be executed immediately rather than deferred
AFAIK the callback invoked by RTC.wakeup is scheduled for later execution rather than being executed immediately, as the pin interrupts are.
See: https://github.com/micropython/micropython/blob/master/ports/stm32/extint.c#L657
IMHO this is undesirable behaviour. If the RTC is used to (a) wake the processor after machine.sleep() and (b) set a flag to be inspected by the main thread, then it has the effect that the flag may not be ready for inspection.
The code below illustrated the problem. I find that for correct operation it is necessary to add a delay after execution resumes and before inspecting variables changed by the callback. Commenting out the delay at line 17 results in undesirable behaviour.
I ran this on an OpenMV camera and the OpenMV github issue here provides more details of how I found this bug/feature, and some further analysis https://github.com/openmv/openmv/issues/1032
`
import machine, pyb, time
global triggered
triggered = False
def callback(arg):
global triggered
triggered = True
pyb.RTC().wakeup(1000, callback)
while (True):
machine.sleep()
# At this point the RTC will have woken us but the callback may not have been executed.
# This delay is essential to allow the callback to execute and update 'triggered'
time.sleep_ms(1) # Required minimum delay is not known. Do not use sleep_us()
if (triggered):
# Toggle green LED to indicate correct behaviour.
# 'triggered' is seen as having changed
pyb.LED(2).toggle()
else:
# Toggle red LED to indicate incorrect behaviour.
# 'triggered' is NOT seen as having changed
pyb.LED(1).toggle()
triggered = False
`
Unexpected Pyboard behaviour around pyb.stop() and rtc.wakeup()
The following seems indicative of a bug. The script runs as expected only if a 10mS or longer delay is placed in the penultimate line. With a delay of 1mS the blue LED remains on almost continuously, only rarely going out for a second. Intermediate values result in erratic operation. The power consumption of the Pyboard indicates that the code is running every second yet the LED is not reliably extinguished. Puzzling as the LED is turned off before the function call.
import pyb
rtc = pyb.RTC()
rtc.datetime((2015, 8, 6, 4, 13, 0, 0, 0))
usb_connected = pyb.Pin.board.USB_VBUS.value() == 1
def lpdelay(ms): # attempt at a low power delay
rtc.wakeup(ms)
pyb.stop()
rtc.wakeup(None)
if not usb_connected:
led = pyb.LED(4)
while True:
led.on()
pyb.delay(1000)
led.off()
pyb.delay(1) # why?
lpdelay(1000)