|
| 1 | +# Initializes SD card and mounts it to the filesystem. This assumes the SD card |
| 2 | +# is on the same SPI bus as the display with a different chip select pin. You |
| 3 | +# may need to adjust this based on your specific board and configuration |
| 4 | + |
| 5 | +# Import the Pin class for the chip select pin |
| 6 | +from machine import Pin |
| 7 | + |
| 8 | +# Import the SPI bus |
| 9 | +from .bus_spi import spi |
| 10 | + |
| 11 | +# When the SD card is initialized, it changes the SPI bus baudrate. We'll |
| 12 | +# want to revert it, so we need to know the original baudrate. There's no |
| 13 | +# way to get it directly, so we convert the bus to a string and parse it. |
| 14 | +# Example format: |
| 15 | +# "SPI(0, baudrate=24000000, sck=Pin(2), mosi=Pin(3), miso=Pin(4))" |
| 16 | +spi_str = str(spi) |
| 17 | +baudrate = int(spi_str[spi_str.index("baudrate=") + 9:].partition(",")[0]) |
| 18 | + |
| 19 | +# Set the chip select pin for the SD card |
| 20 | +sd_cs = Pin(7, Pin.OUT) |
| 21 | + |
| 22 | +try: |
| 23 | + # Import the SD card module. This is often not installed by default in |
| 24 | + # MicroPython, so you may need to install it manually. For example, you can |
| 25 | + # use `mpremote mip install sdcard` |
| 26 | + import sdcard |
| 27 | + |
| 28 | + # Initialize the SD card, then restore the original SPI bus baudrate. This |
| 29 | + # is wrapped in a try/finally block to ensure the baudrate is restored even if |
| 30 | + # the SD card initialization fails |
| 31 | + try: |
| 32 | + sd_card = sdcard.SDCard(spi, sd_cs) |
| 33 | + finally: |
| 34 | + spi.init(baudrate = baudrate) |
| 35 | + |
| 36 | + # Mount the SD card to the filesystem under the "/sd" directory, which makes |
| 37 | + # it accessible just like the normal MicroPython filesystem |
| 38 | + import uos |
| 39 | + vfs = uos.VfsFat(sd_card) |
| 40 | + uos.mount(vfs, "/sd") |
| 41 | +except ImportError: |
| 42 | + print("sdcard module not found, skipping SD card initialization...") |
| 43 | +except OSError as e: |
| 44 | + eStr = str(e) |
| 45 | + if "no SD card" in eStr: |
| 46 | + print("no SD card found, skipping SD card initialization...") |
| 47 | + elif "Errno 1" in eStr: |
| 48 | + print("SD card already mounted, skipping SD card initialization...") |
| 49 | + else: |
| 50 | + print("Failed to mount SD card, skipping SD card initialization...") |
0 commit comments