AJB2K3
Published © CC BY-ND

Micro SD cards with the M5StampS3

How to use Micro SD cards with the M5Stamp S3

IntermediateProtip1 hour221
Micro SD cards with the M5StampS3

Story

Read more

Code

Test code for reading and writing to SD cards.

MicroPython
import machine
from machine import Pin, SPI, SDCard
import os

sd = machine.SDCard(slot=2, width=1, cd=None, wp=None, sck=Pin(6), miso=Pin(4), mosi=Pin(5), cs=Pin(7), freq=10000000)

try:
    os.mount(sd, "/sd")
except:
    print("Failed to mount SD card”)


def print_directory(path, tabs = 0):
    for file in os.listdir(path):
        stats = os.stat(path+"/"+file)
        filesize = stats[6]
        isdir = stats[0] & 0x4000
    
        if filesize < 1000:
            sizestr = str(filesize) + " by"
        elif filesize < 1000000:
            sizestr = "%0.1f KB" % (filesize/1000)
        else:
            sizestr = "%0.1f MB" % (filesize/1000000)
    
        prettyprintname = ""
        for i in range(tabs):
            prettyprintname += "   "
        prettyprintname += file
        if isdir:
            prettyprintname += "/"
        print('{0:<40} Size: {1:>10}'.format(prettyprintname, sizestr))
        
        # recursively print directory contents
        if isdir:
            print_directory(path+"/"+file, tabs+1)


print("Files on filesystem:")
print("====================")
print_directory(/sd")

with open('/sd/letters.txt', 'r') as file:
    data = file.read()
    print(data)

with open('/sd/letters.txt', 'w') as file:
    file.write("Hello, MicroPython!”)


os.umount(/sd")

Credits

AJB2K3

AJB2K3

46 projects • 29 followers
I have always had an interest in electronics but having failed my school exams, it has taken me 20+ years to produce products to share.

Comments