Introduction

Documentation Status Discord Build Status

CircuitPython driver for SD cards. This implements the basic reading and writing block functionality needed to mount an SD card using storage.VfsFat.

Dependencies

This driver depends on:

Please ensure all dependencies are available on the CircuitPython filesystem. This is easily achieved by downloading the Adafruit library and driver bundle.

Usage Example

Mounting a filesystem on an SD card so that its available through the normal Python ways is easy.

Below is an example for the Feather M0 Adalogger. Most of this will stay the same across different boards with the exception of the pins for the SPI and chip select (cs) connections.

import adafruit_sdcard
import busio
import digitalio
import board
import storage

# Connect to the card and mount the filesystem.
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
cs = digitalio.DigitalInOut(board.SD_CS)
sdcard = adafruit_sdcard.SDCard(spi, cs)
vfs = storage.VfsFat(sdcard)
storage.mount(vfs, "/sd")

# Use the filesystem as normal.
with open("/sd/test.txt", "w") as f:
    f.write("Hello world\n")

Sharing the SPI bus with other devices

Important

If the same SPI bus is shared with other peripherals, it is important that the SD card be initialized before accessing any other peripheral on the bus. Failure to do so can prevent the SD card from being recognized until it is powered off or re-inserted.

Contributing

Contributions are welcome! Please read our Code of Conduct before contributing to help this project stay welcoming.

Documentation

For information on building library documentation, please check out this guide.

Table of Contents

Simple test

Ensure your device works with this simple test.

examples/sd_read_simpletest.py
 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import os
import busio
import digitalio
import board
import storage
import adafruit_sdcard

# The SD_CS pin is the chip select line.
#
#     The Adalogger Featherwing with ESP8266 Feather, the SD CS pin is on board.D15
#     The Adalogger Featherwing with Atmel M0 Feather, it's on board.D10
#     The Adafruit Feather M0 Adalogger use board.SD_CS
#     For the breakout boards use any pin that is not taken by SPI

SD_CS = board.SD_CS  # setup for M0 Adalogger; change as needed

# Connect to the card and mount the filesystem.
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
cs = digitalio.DigitalInOut(SD_CS)
sdcard = adafruit_sdcard.SDCard(spi, cs)
vfs = storage.VfsFat(sdcard)
storage.mount(vfs, "/sd")

# Use the filesystem as normal! Our files are under /sd

# This helper function will print the contents of the 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) + " bytes"
        elif filesize < 1000000:
            sizestr = "%0.1f KB" % (filesize / 1000)
        else:
            sizestr = "%0.1f MB" % (filesize / 1000000)

        prettyprintname = ""
        for _ 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")

adafruit_sdcard - SD card over SPI driver

CircuitPython driver for SD cards using SPI bus.

Requires an SPI bus and a CS pin. Provides readblocks and writeblocks methods so the device can be mounted as a filesystem.

  • Author(s): Scott Shawcroft

Implementation Notes

Hardware:

Software and Dependencies:

class adafruit_sdcard.SDCard(spi, cs, baudrate=1320000)[source]

Controls an SD card over SPI.

Parameters:
  • spi (SPI) – The SPI bus
  • cs (DigitalInOut) – The chip select connected to the card
  • baudrate (int) – The SPI data rate to use after card setup

Example usage:

import busio
import storage
import adafruit_sdcard
import os
import board

spi = busio.SPI(SCK, MOSI, MISO)
sd = adafruit_sdcard.SDCard(spi, board.SD_CS)
vfs = storage.VfsFat(sdcard)
storage.mount(vfs, '/sd')
os.listdir('/')
count()[source]

Returns the total number of sectors.

Returns:The number of 512-byte blocks
Return type:int
readblocks(start_block, buf)[source]

Read one or more blocks from the card

Parameters:
  • start_block (int) – The block to start reading from
  • buf (bytearray) – The buffer to write into. Length must be multiple of 512.
writeblocks(start_block, buf)[source]

Write one or more blocks to the card

Parameters:
  • start_block (int) – The block to start writing to
  • buf (bytearray) – The buffer to write into. Length must be multiple of 512.
adafruit_sdcard.calculate_crc(message)[source]

Calculate the CRC of message[0:5], using a precomputed table in CRC_TABLE. :param bytearray message: Where each index is a byte

Indices and tables