|
| 1 | +import os |
| 2 | +import machine |
| 3 | + |
| 4 | +sdcard = None |
| 5 | + |
| 6 | +# This gets called by (the device-specific) boot*.py |
| 7 | +def inform_sdcard(so): |
| 8 | + global sdcard |
| 9 | + sdcard = so |
| 10 | + |
| 11 | +def format_sdcard(sdcard): |
| 12 | + """Format the SD card with FAT filesystem""" |
| 13 | + try: |
| 14 | + print("Formatting SD card...") |
| 15 | + # Unmount if already mounted |
| 16 | + try: |
| 17 | + os.umount('/sdcard') |
| 18 | + except: |
| 19 | + pass |
| 20 | + |
| 21 | + # Format the SD card (this erases all data!) |
| 22 | + sdcard.format() |
| 23 | + print("SD card formatted successfully") |
| 24 | + return True |
| 25 | + except Exception as e: |
| 26 | + print(f"WARNING: Failed to format SD card: {e}") |
| 27 | + return False |
| 28 | + |
| 29 | +# Tries to mount and returns True if it worked |
| 30 | +def try_mount(sdcard): |
| 31 | + try: |
| 32 | + os.mount(sdcard, '/sdcard') |
| 33 | + print("SD card mounted successfully at /sdcard") |
| 34 | + return True |
| 35 | + except Exception as e: |
| 36 | + print(f"WARNING: failed to mount SD card: {e}") |
| 37 | + return False |
| 38 | + |
| 39 | +# Returns True if everything successful, otherwise False if it failed to mount |
| 40 | +def mount_sdcard_optional_format(): |
| 41 | + global sdcard # should have been initialized by inform_sdcard() |
| 42 | + |
| 43 | + if not sdcard: |
| 44 | + print("WARNING: no machine.SDCard object has been initialized at boot, aborting...") |
| 45 | + return False |
| 46 | + |
| 47 | + # Try to detect SD card |
| 48 | + try: |
| 49 | + sdcard.info() |
| 50 | + print("SD card detected") |
| 51 | + except Exception as e: |
| 52 | + print(f"WARNING: sdcard.info() got exception: {e}") |
| 53 | + print("SD card not detected or hardware issue") |
| 54 | + return False |
| 55 | + |
| 56 | + if not try_mount(sdcard): |
| 57 | + if format_sdcard(sdcard): |
| 58 | + if not try_mount(sdcard): |
| 59 | + print(f"WARNING: failed to mount SD card even after formatting, aborting...") |
| 60 | + return False |
| 61 | + else: |
| 62 | + print("WARNING: Could not format SD card - check hardware connections or reformat on a PC. Aborting...") |
| 63 | + return False |
| 64 | + |
| 65 | + try: |
| 66 | + print("SD card contents:", os.listdir('/sdcard')) |
| 67 | + except Exception as e: |
| 68 | + print(f"WARNING: SD card did not fail to mount but could not list SD card contents: {e}") |
| 69 | + return False |
| 70 | + |
| 71 | + print("SD card mounted successfully!") |
| 72 | + return True |
0 commit comments