CircuitPython to list files in SD
CircuitPython exercise to list files in SD
Connection:
Raspberry Pi Pico 2 W
=====================
GP28|
GND |
GP27|
GP26|
Run |
GP22|
GND |
GP21|
GP20|
+------- SD_MISO|GP12 GP19|
| +----- SD_CS |GP13 GP18|
| | |GND GND |
| | +--- SD_SCK |GP14 GP17|
| | | +- SD_MOSI|GP15 GP16|
| | | | +---------------+
| | | |
| | | | SD Module
| | | | =========
| | | | GND --- GND
+-|-|-|-------- MISO
| +-|-------- CLK
| +-------- MOSI
+------------ CS
3V3 --- 3V3
Exercise Code:
cpy_rpPicoW_sd.py
"""
Raspberry Pi Pico 2 W/CircuitPython 10.0.3
with SD Card module.
List files in SD.
"""
import os, sys
import board
import busio
import sdcardio
import storage
sd_miso = board.GP12
sd_cs = board.GP13
sd_clk = board.GP14
sd_mosi = board.GP15
info = os.uname()[4] + "\n" + \
sys.implementation[0] + " " + os.uname()[3]
print("=======================================")
print(info)
print("=======================================")
# Init SD
sd_spi = busio.SPI(clock=sd_clk, MOSI=sd_mosi, MISO=sd_miso)
sd = sdcardio.SDCard(sd_spi, sd_cs)
vfs = storage.VfsFat(sd)
storage.mount(vfs, '/sd')
def list_dir(path, indent=0):
"""Recursive SD card walker (like a mini os.walk())"""
for name in os.listdir(path):
full_path = path + "/" + name
st = os.stat(full_path)
mode = st[0]
if mode & 0x4000: # directory
print(" " * indent + "[DIR] " + name)
list_dir(full_path, indent + 1) # recurse into subfolder
else:
print(" " * indent + name)
def list_files_with_ext(path, ext):
"""Return sorted list of files in path with given extension."""
files = []
for name in os.listdir(path):
full_path = path + "/" + name
st = os.stat(full_path)
mode = st[0]
# check regular file (0x8000) only
if mode & 0x8000:
if name.lower().endswith("." + ext.lower()):
files.append(name)
files.sort()
return files
# usage
list_dir("/sd")
print()
bmp_files = list_files_with_ext("/sd/bmp", "bmp")
print(bmp_files)
gif_files = list_files_with_ext("/sd/GIFs_10", "gif")
print(gif_files)

Comments
Post a Comment