Page 1 of 1

elegant shutdown on battery

Posted: Sun Mar 12, 2017 7:53 am
by icenov
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?

Re: elegant shutdown on battery

Posted: Mon Mar 13, 2017 7:49 am
by shaoziyang
You may read a user switch (or in a external interrupt), to pause ADC sample, then close file.

Re: elegant shutdown on battery

Posted: Mon Mar 13, 2017 8:44 am
by pythoncoder
Something along the lines of:

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()
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.

Re: elegant shutdown on battery

Posted: Tue Mar 14, 2017 10:39 am
by icenov
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!