SD Card wont init or do anything
-
I have a M5Stack Core Basic 2.7. I am attempting to use the SD card slot. It is a 16GB SDHC card that is formatted to FAT32. I created a simple block code in UIFlow2.0 that is:
Setup(Init Built in hardware->Init SD Card->Print(SDCard Listdir()). Init SD card is defined as:
sdcard.SDCard(slot=2, width=1, sck=18, miso=19, mosi=23, cs=4, freq=1000000)This gives the error of:
[Errno 22] EINVAL
E (3390) spi: spi_bus_initialize(758): SPI bus already initialized.
File "hardware/sdcard.py", line 21, in sdcard
OSError: (-259, 'ESP_ERR_INVALID_STATE')I tried adding a spi.deinit block but this doesn't even seem to be in the source code.
I have also tried the test_sdcard.py file in the uiflow-micropython repo and same thing happens.
What am I doing wrong? I have had this working on the same board and SD card with arduino but the micropython one doesn't seem to work at all.
Here is the code as well:import os, sys, io import M5 from M5 import * from hardware import sdcard label0 = None def setup(): global label0 M5.begin() Widgets.fillScreen(0x222222) label0 = Widgets.Label("label0", 117, 208, 1.0, 0xffffff, 0x222222, Widgets.FONTS.DejaVu18) sdcard.SDCard(slot=2, width=1, sck=18, miso=19, mosi=23, cs=4, freq=1000000) print(os.listdir('/sdcard/')) def loop(): global label0 M5.update() if __name__ == '__main__': try: setup() while True: loop() except (Exception, KeyboardInterrupt) as e: try: from utility import print_error_msg print_error_msg(e) except ImportError: print("please update to latest firmware") -
import os, sys, io import M5 from M5 import * from hardware import sdcard label0 = None def setup(): global label0 M5.begin() Widgets.fillScreen(0x222222) label0 = Widgets.Label("label0", 21, 46, 1.0, 0xffffff, 0x222222, Widgets.FONTS.DejaVu18) sdcard.SDCard(slot=2, width=1, sck=18, miso=19, mosi=23, cs=4, freq=1000000) label0.setText(str(os.listdir('/sd/'))) def loop(): global label0 M5.update() if __name__ == '__main__': try: setup() while True: loop() except (Exception, KeyboardInterrupt) as e: try: from utility import print_error_msg print_error_msg(e) except ImportError: print("please update to latest firmware") -
This code works on the SD card for me, Remember to format Fat32 and keep device size 32GB or less
import machine import os import time # --- Configuration for M5Stack CoreS3 SD Card --- SD_SCK = 36 SD_MISO = 35 SD_MOSI = 37 SD_CS = 4 # Configuration for machine.SDCard SD_SLOT = 2 # Typically used for SPI access on ESP32/S3 SD_FREQ = 1000000 # 1MHz frequency for reliable initialization MOUNT_POINT = "/sd" TEST_FILE_PATH = MOUNT_POINT + "/cores3_test_log.txt" def initialize_and_mount_sd(): """Initializes the SD card interface and mounts the filesystem.""" print("Attempting to initialize SD card...") try: # Initialize the SDCard object using the specific pins for the CoreS3 sd = machine.SDCard( slot=SD_SLOT, sck=machine.Pin(SD_SCK), miso=machine.Pin(SD_MISO), mosi=machine.Pin(SD_MOSI), cs=machine.Pin(SD_CS), freq=SD_FREQ ) print("Hardware initialized.") # Mount the SD card filesystem (VfsFat) vfs = os.VfsFat(sd) os.mount(vfs, MOUNT_POINT) print(f"SD Card successfully mounted at {MOUNT_POINT}") return vfs except Exception as e: print(f"ERROR initializing or mounting SD card: {e}") print("Please ensure the SD card is inserted correctly and formatted (FAT32).") return None def write_demo(filepath): """Writes sample data to a file on the SD card.""" print(f"\n--- Writing Demo ---") content = "Hello from M5Stack CoreS3!\n" content += f"MicroPython SD Card Test.\nTimestamp: {time.time()}" try: # Open the file in write mode ('w') with open(filepath, "w") as f: bytes_written = f.write(content) print(f"Successfully wrote {bytes_written} bytes to {filepath}") return True except Exception as e: print(f"ERROR writing to file: {e}") return False def read_demo(filepath): """Reads data from the file on the SD card.""" print(f"\n--- Reading Demo ---") try: # Open the file in read mode ('r') with open(filepath, "r") as f: data = f.read() print(f"Contents of {filepath}:") print("-" * 30) print(data) print("-" * 30) except Exception as e: print(f"ERROR reading from file: {e}") def list_directory_demo(path): """Lists the contents of the directory with file sizes.""" print(f"\n--- Directory Listing Demo ({path}) ---") try: items = os.listdir(path) if not items: print("(Empty Directory)") return print(f"{'Name':<25} {'Size (Bytes)':>15}") print("-" * 41) for item in items: try: # os.stat returns a tuple; index 6 contains the file size stats = os.stat(path + "/" + item) size = stats[6] print(f"{item:<25} {size:>15}") except Exception as e: print(f"{item:<25} (Error getting stats)") except Exception as e: print(f"ERROR listing directory: {e}") def unmount_sd(mount_point): """Unmounts the SD card filesystem.""" print("\n--- Unmounting ---") try: # Crucial to prevent corruption os.umount(mount_point) print("SD Card unmounted successfully.") except Exception as e: print(f"ERROR unmounting SD Card: {e}") def main(): print("Starting M5Stack CoreS3 SD Card Demo") # 1. Initialize and Mount vfs = initialize_and_mount_sd() if vfs: # 2. List initial contents list_directory_demo(MOUNT_POINT) # 3. Write data if write_demo(TEST_FILE_PATH): # 4. Read data back read_demo(TEST_FILE_PATH) # 5. List contents again to show the new file and size list_directory_demo(MOUNT_POINT) # 6. Unmount unmount_sd(MOUNT_POINT) else: print("Demo aborted due to SD card initialization failure.") if __name__ == "__main__": main() -
Thank you so much for posting this. This works perfectly for my M5 Paper as well (changing out the hardware numbers as needed). I was able to write some custom blocks based on this. <3
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login