sdcard — SD card
Secure Digital or SD cards and micro microSD cards are inexpensive and can add a large amount of storage space to a device. MicroPython has only 1M of flash to store code and data. If you have larger flash space, you can connect a micro SD card to the mPython Board via SPI communication to expand its storage space.
Note
SD card – the image must be viewed online: 520920e2-79cd-4b23-8e89-1acc572496e8
SDCard Class
- class sdcard.SDCard(spi, cs)
Create an SDCard object and initialize the SD card.
First, ensure that the pins of the SPI bus are physically connected correctly to the micro SD card. Make sure your micro SD card is formatted with the FAT or FAT32 file system. Then, use os.mount() to mount the SD card’s new virtual FAT file system to the specified directory. After mounting, you can use Python’s file operations (such as open, close, read, and write) to access files.
spi- The machine.SPI objectcs- The CS control pin of the SPI
1from machine import Pin, SPI
2import machine, sdcard, os
3
4# Create SPI object, SPI pins as follows
5spi = SPI(1, baudrate=10000000, polarity=0, phase=0, sck=Pin(Pin.P13), mosi=Pin(Pin.P15), miso=Pin(Pin.P14))
6# Create SDCard object
7sd = sdcard.SDCard(spi, Pin(Pin.P16))
8# Mount SD to '/sd' path
9os.mount(sd, '/sd')
10
11# Create file and write data
12with open("/sd/test.txt", "w") as f:
13 f.write("Hello world!\r\n")
1from machine import Pin, SPI
2import machine, sdcard, os
3
4spi = SPI(1, baudrate=10000000, polarity=0, phase=0, sck=Pin(Pin.P13), mosi=Pin(Pin.P15), miso=Pin(Pin.P14))
5sd = sdcard.SDCard(spi, Pin(Pin.P16))
6
7os.mount(sd, '/sd')
8
9def print_directory(path, tabs = 0):
10 for file in os.listdir(path):
11 stats = os.stat(path+"/"+file)
12 filesize = stats[6]
13 isdir = stats[0] & 0x4000
14
15 if filesize < 1000:
16 sizestr = str(filesize) + " by"
17 elif filesize < 1000000:
18 sizestr = "%0.1f KB" % (filesize/1000)
19 else:
20 sizestr = "%0.1f MB" % (filesize/1000000)
21
22 prettyprintname = ""
23 for i in range(tabs):
24 prettyprintname += " "
25 prettyprintname += file
26 if isdir:
27 prettyprintname += "/"
28 print('{0:<40} Size: {1:>10}'.format(prettyprintname, sizestr))
29
30 # recursively print directory contents
31 if isdir:
32 print_directory(path+"/"+file, tabs+1)
33
34
35print("Files on filesystem:")
36print("====================")
37print_directory("/sd")
38