86 lines
2.5 KiB
Python
86 lines
2.5 KiB
Python
"""CircuitPython SD card utility using sdioio and storage.
|
|
|
|
Uses SDMMC 1-bit mode on Pins: sck=board.IO2, cmd=board.IO1, data0=board.IO3.
|
|
"""
|
|
|
|
import os
|
|
import board
|
|
import sdioio
|
|
import storage
|
|
|
|
class SDCardManager:
|
|
def __init__(self, mount_point='/sd'):
|
|
self.mount_point = mount_point
|
|
self.sd = None
|
|
self.mounted = False
|
|
|
|
def mount(self):
|
|
if self.mounted:
|
|
print(f"SD card already mounted at {self.mount_point}")
|
|
return True
|
|
|
|
try:
|
|
print("Initializing SDCard (SDMMC 1-bit mode: sck=2, cmd=1, d0=3)...")
|
|
self.sd = sdioio.SDCard(clock=board.IO2, command=board.IO1, data=[board.IO3], frequency=20000000)
|
|
vfs = storage.VfsFat(self.sd)
|
|
print(f"Mounting SD card to {self.mount_point}...")
|
|
storage.mount(vfs, self.mount_point)
|
|
self.mounted = True
|
|
print("SD card mounted successfully!")
|
|
return True
|
|
except Exception as e:
|
|
print(f"Failed to mount SD card: {e}")
|
|
self.sd = None
|
|
self.mounted = False
|
|
return False
|
|
|
|
def unmount(self):
|
|
if not self.mounted:
|
|
return True
|
|
|
|
try:
|
|
print(f"Unmounting SD card from {self.mount_point}...")
|
|
storage.umount(self.mount_point)
|
|
if self.sd:
|
|
try:
|
|
self.sd.deinit()
|
|
except:
|
|
pass
|
|
self.mounted = False
|
|
self.sd = None
|
|
print("SD card unmounted.")
|
|
return True
|
|
except Exception as e:
|
|
print(f"Failed to unmount SD card: {e}")
|
|
return False
|
|
|
|
def is_mounted(self):
|
|
return self.mounted
|
|
|
|
def list_files(self):
|
|
if not self.mounted:
|
|
print("SD card is not mounted.")
|
|
return None
|
|
try:
|
|
return os.listdir(self.mount_point)
|
|
except Exception as e:
|
|
print(f"Error listing SD card files: {e}")
|
|
return None
|
|
|
|
def get_info(self):
|
|
if not self.mounted:
|
|
return None
|
|
try:
|
|
stat = os.statvfs(self.mount_point)
|
|
block_size = stat[0]
|
|
total_blocks = stat[2]
|
|
free_blocks = stat[3]
|
|
|
|
return {
|
|
"total_bytes": total_blocks * block_size,
|
|
"free_bytes": free_blocks * block_size
|
|
}
|
|
except Exception as e:
|
|
print(f"Error getting SD card info: {e}")
|
|
return None
|