Preserving settings as initials for a new session

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Ruedi
Posts: 10
Joined: Tue Feb 21, 2017 2:34 pm

Preserving settings as initials for a new session

Post by Ruedi » Mon Apr 10, 2017 2:35 pm

Hi, out there. Maybe someone can present the decisive hint to achieve this:
I want to preserve values arrived by lcd.get_touch() in RAM and/or in main.py to be used as initial settings for a new session. And this is what I tried (the following is examplary):

In main.py I declared a list exch=[0, 1, 2]
With my script I get and write a new value into position 1 in exch (which is now a local list) using
exch.pop(1)
exch.insert(1,newvalue)
which is working fine

How can I now update the global list to the new value to use it after a reboot or to use it in a different part of the script during a session. To declare exch as global didn't work, maybe I used a wrong syntax. What is the right one?

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Preserving settings as initials for a new session

Post by pythoncoder » Tue Apr 11, 2017 6:38 am

Rather than pop() and insert() it's clearer and more efficient to write

Code: Select all

exch[1] = newvalue
To preserve the list across reboots and times when the board is powered down you need to save it as a file.

Code: Select all

import ujson
with open('/flash/myfile', 'w') as f:
	f.write(ujson.dumps(exchg))
This only needs to be repeated if the data changes.

Then any module wanting to access the saved list can issue

Code: Select all

import ujson
with open('/flash/myfile', 'r') as f:
	exchg = ujson.loads(f.read())
Peter Hinch
Index to my micropython libraries.

Ruedi
Posts: 10
Joined: Tue Feb 21, 2017 2:34 pm

Re: Preserving settings as initials for a new session

Post by Ruedi » Tue Apr 11, 2017 5:19 pm

Hi pythoncoder
Thanks a lot, your advice was very helpful

Post Reply