elegant shutdown on battery
elegant shutdown on battery
On pyboard v1.1 using battery only supply, I am running a script that reads the ADC and writes the value to file (on sd card) every second. I would like to occasionally remove the card and read the file contents. Is there a way to shutdown the script and close the file without just pulling the power plug? I am thinking of using the user switch to send a signal to exit the script and power down. Does that make sense?
-
- Posts: 363
- Joined: Sun Apr 17, 2016 1:55 pm
Re: elegant shutdown on battery
You may read a user switch (or in a external interrupt), to pause ADC sample, then close file.
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: elegant shutdown on battery
Something along the lines of:
The context manager (with statement) ensures the file is closed. The LED confirms that the switch press has been registered and the file closed. As written the code will append to an existing file. It will also require the button to be pressed for a second to be sure it is recognised: you could poll it 10 times per file write (say) to fix this.
[EDIT]Fix half-baked code.
Code: Select all
import pyb
sw = pyb.Switch()
led = pyb.LED(2)
with open('myfile.txt', 'a') as f: # Append mode.
while not sw():
# get data, write to f, pause one second
led.on()
[EDIT]Fix half-baked code.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.
Re: elegant shutdown on battery
Thank you pythoncoder - that worked well. I slightly modified it that defined a function that set a global variable to True, then setup the rest of the code in a While loop to check the state of the variable.
def f():
pyb.LED(1).toggle() # activate LED to acknowledge switch press
print('Switch pressed: Exiting script')
global switchpress
switchpress = 1
sw.callback(f)
On switchpress the file is closed .
while switchpress == 0:
count += 1
...
Script now closes properly!
def f():
pyb.LED(1).toggle() # activate LED to acknowledge switch press
print('Switch pressed: Exiting script')
global switchpress
switchpress = 1
sw.callback(f)
On switchpress the file is closed .
while switchpress == 0:
count += 1
...
Script now closes properly!