write to filesystem in interrupt

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

write to filesystem in interrupt

Post by devnull » Sun Feb 19, 2017 2:27 pm

I have a push-button interrupt that detects short and long presses.

If long press, then I need to restart the device in setup mode, otherwise I start it in run mode.

The boot.py initialises the interrupt and during startup reads a json file, if the mode in the json config is set to run then it will execute the run library otherwise it will execute the setup library.

All of this works fine if I manually edit the .json variable, the problem is I cannot write to the .json file during the button press interrupt routine.

Any suggestions on an alternative method of selecting run / setup modes during boot with the ability to trigger the system to reboot and run the correct mode or how I can write the mode to the json file

Code: Select all

rmode = 'run'
startms = 0
def pincb(pin):
  global rmode, run, startms
  if(pin()==0 and startms==0):
    startms = ticks_ms()
    while ticks_diff(ticks_ms(),startms) < 200: pass
    while pin() == 0: pass
    if(ticks_diff(ticks_ms(),startms)>1050): rmode = 'setup'
    startms = 0
    jsonWrite('mode':rmode) ## << can't do this !
    machine.reset()

def pininit():
  but = Pin(13, Pin.IN, Pin.PULL_UP)
  but.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=pincb)
  
data = jsonRead()
if(data['mode']=='run'): mqtts()
else: webs()
jsonRead and jsonWrite is just a function that reads / writes the json file, webs() is a http server, mqtts() is a mqtt client, both run forever.

User avatar
deshipu
Posts: 1388
Joined: Thu May 28, 2015 5:54 pm

Re: write to filesystem in interrupt

Post by deshipu » Sun Feb 19, 2017 8:09 pm

The usual way of dealing with such problems is to only set a flag inside the interrupt, and then, in your program's main loop, check that flag and perform the actual file writing and restart if it is set.

User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

Re: write to filesystem in interrupt

Post by devnull » Mon Feb 20, 2017 1:49 am

@deshipu - thanks for the suggestion, but what I eventually ended up doing is calling a ONE_SHOT timer from the interrupt, it seems to work reliably and I don't need to detect it in a loop.

Post Reply