sdcard — SD Card

Secure digital or SD cards and micro microSD cards are inexpensive and can add a lot of storage space to the device. MicroPython, only 1M flash memory to store code and data. If you have more flash memory space, you can connect the micro SD card to the control board through SPI communication to expand its storage space.

https://www.digikey.com/maker-media/520920e2-79cd-4b23-8e89-1acc572496e8

SD Card

SDCard class

class sdcard.SDCard(spi, cs)

Create SDCard object, initialize SD card.

First, make sure that the pins of the SPI bus are physically connected to the micro SD card correctly. Make sure your micro SD card is formatted with FAT or FAT32 file system. Then, use os.mount() to mount the virtual new FAT file system of the SD card into the specified directory. After the mount is complete, you can use Python’s file operations (such as open, close, read, and write) to access the file.

  • spi - machine.SPI object
  • cs - SPI CS control pin
example - mount SD card
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from machine import Pin, SPI
import machine, sdcard, os

# 创建SPI对象,spi引脚如下述
spi = SPI(1, baudrate=10000000, polarity=0, phase=0, sck=Pin(Pin.P13), mosi=Pin(Pin.P15), miso=Pin(Pin.P14))
# 构建SDCard对象
sd = sdcard.SDCard(spi, Pin(Pin.P16))
# 挂载sd到 '/sd' 路径
os.mount(sd, '/sd')

# 创建文件并写数据
with open("/sd/test.txt", "w") as f:
    f.write("Hello world!\r\n")
example - lsit all files
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from machine import Pin, SPI
import machine, sdcard, os

spi = SPI(1, baudrate=10000000, polarity=0, phase=0, sck=Pin(Pin.P13), mosi=Pin(Pin.P15), miso=Pin(Pin.P14))
sd = sdcard.SDCard(spi, Pin(Pin.P16))

os.mount(sd, '/sd')

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