def switch_filesystem(): """Method to enable file IO on the internal storage of the microcontroller""" # Detect if the console is connected # NOTE: This is a bad indicator of if the filesystem should be readonly. # There is potential to lock the USB interface out disabling updates. # print("USB Status was: {0}".format(supervisor.runtime.serial_connected)) # A more reliable method is to use a switch, I attached on to D2 input simply # because it was easy to solder in place and use the ground wire used for the # gyro sensor switch = digitalio.DigitalInOut(board.D2) switch.direction = digitalio.Direction.INPUT switch.pull = digitalio.Pull.UP # If the D2 switch is connected to ground with a wire try: if switch.value: print("Remounting Filesystem for readonly") storage.remount("/", readonly=True) else: print("Remounting Filesystem for write") storage.remount("/", readonly=False) except RuntimeError as e: print("No change to filesystem. {}".format(e)) switch.deinit()
def _save_config_to_ini(self): import storage ## If MCU is mounted on a host, this call will fail ## and we report the error via returning False (0) to the caller. ## ## CircuitPython 5.2.0 or greater is needed for this process to work. try: storage.remount("/", readonly=False) stdout("Remounted filesystem RW") except RuntimeError as e: stdout("Remount filesystem RW failed") stdout(e) return 0 with open("/config.ini", 'w') as f: for key, value in self.config.items(): if key in _FLOAT_KEYS: value = round(value * _FLOAT_SCALE) elif key not in _STRING_KEYS: value = int(value) f.write(key + " = " + str(value) + "\r\n") stdout("INI file written") storage.remount("/", readonly=True) stdout("Remounted filesystem RO") return 1
def setStorageAccess(): switch = digitalio.DigitalInOut(board.SWITCH) switch.direction = digitalio.Direction.INPUT switch.pull = digitalio.Pull.UP # If the switch pin is connected to ground CircuitPython can write to the drive storage.remount("/", switch.value)
def _store_bitmap(self): try: storage.remount('/', False) except: pass try: bitmap_save('/nametag.bmp', self._bitmap) except Exception as err: print("Couldn't save file: {}".format(err)) try: storage.remount('/', True) except: pass
def copyfloppy(targetfolder, files=None, caption="Copying files...", captionx=60): """ Copy files from a floppy disk into the the badge's local filesystem. Returns True if copying succeeded, False in case of an error (e.g. filesystem can't be mounted for writing). """ try: storage.remount('/', False) except: return False try: os.mkdir(targetfolder) except: pass if not files: files = os.listdir('/floppy') display = badge.display screen = displayio.Group() copying_label = label.Label(terminalio.FONT, text=caption, color=0xffffff) copying_label_group = displayio.Group(scale=2, x=captionx, y=display.height - 60) copying_label_group.append(copying_label) screen.append(copying_label_group) progress_bar = HorizontalProgressBar( (10, display.height - 40), (display.width - 20, 30), min_value=0, max_value=len(files), direction=HorizontalFillDirection.LEFT_TO_RIGHT, ) screen.append(progress_bar) display.show(screen) display.refresh() for filename in files: copyfile('/floppy/{}'.format(filename), '{}/{}'.format(targetfolder, filename)) progress_bar.value += 1 display.show(screen) display.refresh() storage.remount('/', True) return True
def _decorator(self, *args, **kwargs): retval = None try: retval = func(self, *args, **kwargs) return retval except Exception as e: err_str = "ERROR in %s\n%s\n" % (func.__name__, e) if self._settings["log_errors_to_file"]: storage.remount("/", disable_concurrent_write_protection=False) with open(self._error_log_file, "a") as err_log: err_log.write(err_str) storage.remount("/", False) print(err_str) return retval
def save(companbot_x_stat): try: print("Saving") storage.remount("/", False) eventLog = open("save.csv", "w+") eventLog.write( str(companbot_x_stat.xp) + "," + str(companbot_x_stat.lvl) + "," + str(companbot_x_stat.hp) + "," + str(companbot_x_stat.pAtk) + "," + str(companbot_x_stat.pDef) + "," + str(companbot_x_stat.cred) + '\n') eventLog.close() storage.remount("/", True) except Exception as e: print("Error writing log: " + str(e)) storage.remount("/", True) return
import board import digitalio import storage switch = digitalio.DigitalInOut(board.D1) switch.direction = digitalio.Direction.INPUT switch.pull = digitalio.Pull.UP if switch.value is True: output = False else: output = True # If the switch pin is connected to ground (switch is pressed), the computer (not CircuitPython) can write to the drive storage.remount("/", output)
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries # SPDX-License-Identifier: Unlicense """ CircuitPython Essentials Storage CP Filesystem boot.py file """ import board import digitalio import storage pin = digitalio.DigitalInOut(board.A0) pin.switch_to_input(pull=digitalio.Pull.UP) # If the pin is connected to ground, the filesystem is writable by CircuitPython storage.remount("/", readonly=pin.value)
import board import storage from analogio import AnalogIn def read_buttons(): with AnalogIn(board.A3) as ain: reading = ain.value / 65535 if reading > 0.75: return None if reading > 0.4: return 4 if reading > 0.25: return 3 if reading > 0.13: return 2 return 1 readonly = True # if a button is pressed while booting up, CircuitPython can write to the drive button = read_buttons() if button != None: readonly = False if readonly: print("OS has write access to CircuitPython drive") else: print("CircuitPython has write access to drive") storage.remount("/", readonly)
# send any new messages if new_messages: for msg in new_messages: mqtt_client.publish(DATA_TOPIC,json.dumps(new_messages[msg])) # check for mqtt remote messages mqtt_client.loop() # break mqtt connection mqtt_client.disconnect() # if we can't connect, cache message else: for msg in new_messages: new_messages[msg]["N"]=0 # not new try: storage.remount('/',False) with open('/data.txt','a') as f: f.write(json.dumps(new_messages[msg])+'\n') storage.remount('/',True) except: print('Cant cache msg. Connected to usb?') gs.msg_cache=gs.msg_cache+1 gs.counter = gs.counter + 1 print('Finished. Deep sleep until RX interrupt or {}s timeout...'.format(gs.deep_sleep)) # wake up on IRQ or after deep sleep time pin_alarm1 = alarm.pin.PinAlarm(pin=board.IO5, value=True, pull=False) # radio1 pin_alarm2 = alarm.pin.PinAlarm(pin=board.IO6, value=True, pull=False) # radio2 pin_alarm3 = alarm.pin.PinAlarm(pin=board.IO7, value=True, pull=False) # radio3 time_alarm = alarm.time.TimeAlarm(monotonic_time=time.monotonic() + gs.deep_sleep)
### copies of the Software, and to permit persons to whom the Software is ### furnished to do so, subject to the following conditions: ### The above copyright notice and this permission notice shall be included in all ### copies or substantial portions of the Software. ### THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ### IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ### FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ### AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ### LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ### OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ### SOFTWARE. ### Inspired by switch example in ### https://learn.adafruit.com/circuitpython-essentials/circuitpython-storageapproach in import board import digitalio import storage button_a = digitalio.DigitalInOut(board.BUTTON_A) button_a.switch_to_input(pull=digitalio.Pull.UP) if not button_a.value: ### Left button is pressed down, remount CIRCUITPY r/w print("Remounting / read-write") storage.remount("/", readonly=False) else: print("Leaving / as read-only")
import storage import touchio import board import time import digitalio led = digitalio.DigitalInOut(board.D1) led.direction = digitalio.Direction.OUTPUT touch_pad = board.D2 touch = touchio.TouchIn(touch_pad) touched = False led.value = True time.sleep(30) for i in range(100000): if touch.value: touched = True print(touched) storage.remount("/", touched)
This file is specific to boards like ESP32-S2 where the boot button is used for bootloader and safe mode, and therefore the button must be pressed at the right time to get into readonly mode. There are two things to be updated in this file to match your board: * Update OBJECT_PIN to match the pin name to which the button or pin is attached. * Update UP_OR_DOWN to match the Pull necessary for the chosen pin. For example: If using the boot button on a QT Py ESP32-S2, OBJECT_PIN to BUTTON. For example: If using the boot button on a QT Py ESP32-S2, update UP_OR_DOWN to UP. """ import time import board import digitalio import storage import neopixel pixel = neopixel.NeoPixel(board.NEOPIXEL, 1) button = digitalio.DigitalInOut(board.OBJECT_PIN) button.switch_to_input(pull=digitalio.Pull.UP_OR_DOWN) # Turn the NeoPixel white for one second to indicate when to press the boot button. pixel.fill((255, 255, 255)) time.sleep(1) # If the button is connected to ground, the filesystem is writable by CircuitPython storage.remount("/", readonly=button.value)
import storage storage.remount("/", False)
# SPDX-FileCopyrightText: 2020 Dan Cogliano for Adafruit Industries # # SPDX-License-Identifier: MIT import time import storage print("**************** WARNING ******************") print("Using the filesystem as a write-able cache!") print("This is risky behavior, backup your files!") print("**************** WARNING ******************") storage.remount("/", disable_concurrent_write_protection=True) time.sleep(5)
def calibration(old_data): # Calibration method # Calibrates the screen by having the user press the 4 corners of the touchscreen, the corner that is meant to be touched lights up with LEDS # Each corner press has 5 steps # Turn on the corressponding LED # Wait for touch input # Print the x,y,strength of the touch point to the serial com port # Turn off corresponding LED # Save the x and y values (automatically averages out min/max values) # Wait one second ############################ # Start of corner touch calibration # TOP LEFT light_on(top_L) p = calibration_loop() if p == 1: return old_data print(p) light_off(top_L) x_min = p[0] y_min = p[1] time.sleep(1) # TOP RIGHT p = ts.touch_point light_on(top_R) p = calibration_loop() if p == 1: return old_data print(p) light_off(top_R) y_min = (y_min + p[1]) / 2 x_max = p[0] time.sleep(1) # BOTTOM LEFT p = ts.touch_point light_on(bottom_L) p = calibration_loop() if p == 1: return old_data print(p) light_off(bottom_L) x_min = (x_min + p[0]) / 2 y_max = p[1] time.sleep(1) # BOTTOM RIGHT p = ts.touch_point light_on(bottom_R) p = calibration_loop() if p == 1: return old_data print(p) light_off(bottom_R) x_max = (x_max + p[0]) / 2 y_max = (y_max + p[1]) / 2 time.sleep(1) # End of corner touch calibration ####################### # Print the minimium and maximium values onto the serial com port print("X MIN: ", x_min) print("X MAX: ", x_max) print("Y MIN: ", y_min) print("Y MAX: ", y_max) # Use linear algebra to solve the system of two equations to conver the touchscreens 0-65xxx(max 12 bit ADC max value) to the digitizer 0-32767 values temp = solve(x_min, x_max) + solve(y_min, y_max) # Try to save the calibration data onto the flash memory # You need to eject the USB mass storage device with the current firmware build new firmware will be uploaded whent this issue is resolved https://github.com/adafruit/circuitpython/issues/4417 try: storage.remount("/", False) # Try mounting the storage to save # Saves the calibration data for the two y=mx+b as: # m1 b1\nm2 b2 with open("/saved.txt", "w") as fp: fp.write(str(temp[0]) + " " + str(temp[1]) + "\n") fp.write(str(temp[2]) + " " + str(temp[3])) fp.close() storage.remount("/", True) # Unmount the storage except: # If the calibration does not save the yellow LED flashes quickly 3 times but the calibration stays until next power cycle for i in range(3): light_on(yelloww) time.sleep(0.25) light_off(yelloww) time.sleep(0.25) return temp
def __init__(self, measurements, headers=None, filename=None, use_SD=True, spi=None, SD_CS=None): """__init__ :param int measurements: The number of different measurements that will be taken per reading. :param list headers: A list of strings of headers for the different measurements. List length must be equal to `measurements`. If None, headers will not be used. :param string filename: Filename of the log. Defaults to `log.txt` if none is supplied. :param bool use_SD: Whether to write to the SD card or the local filesystem. Defaults to SD. :param spi: A supplied spi bus. Creates it's own if none is supplied. Only used if `use_SD` is `True`. :param SD_CS: The SD card's chip select pin. if none is supplied, it will try the inbuilt `board.SD_CS` """ self.reading_no = 0 self.num_measurements = 0 if headers: assert ( measurements == len(headers) ), "The number of headers must equal the number of different measurements" self.num_measurements = measurements self.headers = ["Reading no"] + headers if filename: self.filename = filename else: self.filename = "log.txt" import storage if use_SD: import adafruit_sdcard, digitalio if spi: self.spi = spi else: import board self.spi = board.SPI() if SD_CS: self.SD_CS = SD_CS else: import board try: self.SD_CS = board.SD_CS except AttributeError: raise AttributeError( "Your board does not have a built in SD card, please supply the chip select pin for the SD card of the addon board" ) self.sdcard = adafruit_sdcard.SDCard( self.spi, digitalio.DigitalInOut(self.SD_CS)) self.vfs = storage.VfsFat(self.sdcard) storage.mount(self.vfs, "/sd") self.filepath = "/sd/" + self.filename else: #print("WARNING!! This will not work unless you have set up boot.py to mount the filesystem as rw, see https://learn.adafruit.com/circuitpython-essentials/circuitpython-storage") try: storage.remount("/") self.filepath = "/" + self.filename except RuntimeError as e: raise RuntimeError( str(e) + "\nLocal filesystem logging will only work when CIRCUITPY is not mounted by a computer" ) # will only work once running a release after https://github.com/adafruit/circuitpython/commit/8e8eb07 try: with open(self.filepath, "r") as f: # check if continuing last log or starting a new one firstline = f.readline().split(",") for index, value in enumerate(firstline): firstline[index] = value.strip() if firstline == self.headers or firstline[0] == "0": for line in f: if line != "\n": lastline = line lastline = lastline.split(",") self.reading_no = int(lastline[0]) + 1 self.num_measurements = len(lastline) - 1 newfileneeded = False else: from os import rename rename(self.filepath, self.filepath + ".old") newfileneeded = True except OSError as e: if e.args[0] == 2: # no such file newfileneeded = True elif e.args[0] == 30: # read only fs raise RuntimeError( "The filesystem has been mounted as read only") if newfileneeded: with open(self.filepath, "w") as f: if headers: f.write(', '.join(str(x) for x in self.headers)) f.write("\n")
import board from analogio import AnalogIn import storage control_pin = AnalogIn(board.A1) allow_coding = True if control_pin.value < 15000: allow_coding = False print(allow_coding) # If the control_pin is set to STOP (i.e. to the top) # CircuitPython can write to the drive storage.remount("/", allow_coding)
import digitalio import board import storage switch = digitalio.DigitalInOut(board.D6) switch.switch_to_input() storage.remount( "/", not switch.value ) # switch.value==False means datalogging mode: allow circuitpython code to write to flash, while making USB read-only. So: pull D6 high for datalogging, leave D6 at ground for USB write access (reprogramming).
# Write your code here :-) import board import digitalio import storage import time switch = digitalio.DigitalInOut(board.D7) # For Circuit Playground Express switch.direction = digitalio.Direction.INPUT switch.pull = digitalio.Pull.UP led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT #led = DigitalInOut(board.D13) #create led which is D13 #led.direction = Direction.OUTPUT #D7 is output digital # If the switch pin is connected to ground CircuitPython can write to the drive # If Switch is LEFT then can write to drive from MU, switch.value is True # If Switch is RIGHT then CAN'T write to drive from MU, # yet can write from Python, switch.value is False storage.remount("/", switch.value) #Now Put on Red LED to show if WRITEABLE from Mu, swich.value is True led.value = not switch.value time.sleep(1) #Pause for a second to show light before loading code.py #print(switch.value)
""" Check for connection between pin and GND on hard boot (power-on or reset). If NO connection: storage is remounted as read/write so the light painter code can run (it requires temporary files), but code.py can't be edited. If connected: storage is left in read-only mode. Light painter code can't run but files are editable. """ # pylint: disable=import-error import board import digitalio import storage PIN = board.D0 IO = digitalio.DigitalInOut(PIN) IO.direction = digitalio.Direction.INPUT IO.pull = digitalio.Pull.UP if IO.value: # No connection storage.remount('/', False) # Remount storage as read/write for painter
""" boot.py file for Pico data logging example. If pin GP0 is connected to GND when the pico starts up, make the filesystem writeable by CircuitPython. """ import board import digitalio import storage write_pin = digitalio.DigitalInOut(board.GP0) write_pin.direction = digitalio.Direction.INPUT write_pin.pull = digitalio.Pull.UP # If the write pin is connected to ground, CircuitPython can write to the CIRCUITPY filesystem. storage.remount("/", write_pin.value)
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries # SPDX-License-Identifier: MIT """ CircuitPython Essentials Storage CP Filesystem boot.py file REMOVE THIS LINE AND ALL TEXT BELOW BEFORE SUBMITTING TO GITHUB. There are three things to be updated in this file to match your board: * Update OBJECT_NAME to match the physical thing you are using, e.g. button or pin. * Update OBJECT_PIN to match the pin name to which the button or pin is attached. * Update UP_OR_DOWN to match the Pull necessary for the chosen pin. For example: If using the up button on a FunHouse, update OBJECT_NAME to button, and OBJECT_PIN to BUTTON_UP. If using pin A0 on a Feather RP2040, update OBJECT_NAME to pin, and OBJECT_PIN to A0. For example: If using the up button on a FunHouse, update UP_OR_DOWN to DOWN. IF using pin A0 on a Feather RP2040, update UP_OR_DOWN to UP. """ import board import digitalio import storage OBJECT_NAME = digitalio.DigitalInOut(board.OBJECT_PIN) OBJECT_NAME.switch_to_input(pull=digitalio.Pull.UP_OR_DOWN) # If the OBJECT_NAME is connected to ground, the filesystem is writable by CircuitPython storage.remount("/", readonly=OBJECT_NAME.value)
from adafruit_circuitplayground.express import cpx import storage # Storage mode based on slide switch. # To the left (music note icon) is True, sets the cpx to USB write mode. # To the right (ear icon) is False, sets the cpx to data logging mode. storage.remount("/", cpx.switch)
import board import digitalio import storage switch = digitalio.DigitalInOut(board.D9) switch.direction = digitalio.Direction.INPUT switch.pull = digitalio.Pull.UP print('D9: {0}'.format(switch.value)) # If the switch is pressed CircuitPython can write to the drive storage.remount('/', switch.value)