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()