Sorry for being clumsy in the coding, I am not well versed in micropython and the lack of examples I could find makes it harder.
I want to do something relatively simple it seems:
board: Pyboard v1.1 firmware 1.11
The program is in lightsleep (to save power) but needs to react within ~ 2ms from a falling edge on a digital pin. Following this falling edge, the code should read the uart, then go back to lightsleep. With the pyb, it seems lightsleep is my only option to react quickly enough (2ms ) and deepsleep would not cut it (too slow to restart the board) despite lower current consumption...
First crack at it is as follows, and the interrupt definition keeps complaining about extra keywords arguments... Aside from this, is the approach sound? While loop sleeping at most time, then waking up on external interrupt, continuing on UART read, then back to sleep. I also think the IRQ sholuld be disabled first thing when waking up, then re-enabled before sleeping . How to do that ? Using machine.enable_irq() and machine.disable_irq() ? Thx. Code below.
Code: Select all
import pyb
from machine import UART, Pin
#Add some leds for tshooting
ledA = pyb.LED(4)
ledA.intensity(15)
ledB = pyb.LED(2)
ledB.intensity(15)
ledA.off()
ledB.off()
#set UART 2 pins are Tx=X3, Rx=X4
uart=UART(2)
uart.init(baudrate=9600,bits=8, stop=1, parity=None, timeout_char=10)
#code called by IRQ, it does not need to do much
def irq_handler(trigpin):
global flag; flag = True
#Defining the pin
trigpin = Pin('Y1', machine.Pin.IN, machine.Pin.PULL_UP)
#Defining the interrupt for the pin
trigpin.irq(handler=irq_handler, trigger=Pin.IRQ_FALLING, priority=1, wake=machine.lightsleep, hard=True)
#Init the interrupt handling
trigpin.init()
while True:
print ('going to light sleep')
#Go to lightsleep immediately, the 20s sleep time is just there in case hw interrupt does not work
machine.lightsleep(20000) # After interrupt, the code should resume from heartbeat
#now we are awake
print('waking up now')
#Somehow we should disable the IRQ while we run through this part of the code, how to do that?
ledA.on()
pyb.delay(1000) # time to see LED and
count=uart.any()
print ('uart count:',count)
if count > 0:
ledB.on()
print('found some uart data: ',uart.read()) # print out the content of the uart
#should loop here to make sure we get all the character
pyb.delay(2000)
ledA.off()
ledB.off()
#We should re-enable the IRQ here