elegant shutdown on battery

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
icenov
Posts: 9
Joined: Sun Mar 12, 2017 1:27 am

elegant shutdown on battery

Post by icenov » Sun Mar 12, 2017 7:53 am

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?

shaoziyang
Posts: 363
Joined: Sun Apr 17, 2016 1:55 pm

Re: elegant shutdown on battery

Post by shaoziyang » Mon Mar 13, 2017 7:49 am

You may read a user switch (or in a external interrupt), to pause ADC sample, then close file.

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

Re: elegant shutdown on battery

Post by pythoncoder » Mon Mar 13, 2017 8:44 am

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.
Peter Hinch
Index to my micropython libraries.

icenov
Posts: 9
Joined: Sun Mar 12, 2017 1:27 am

Re: elegant shutdown on battery

Post by icenov » Tue Mar 14, 2017 10:39 am

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!

Post Reply