Skip to content

Make compatible with native adafruit_bus_device #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 10, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 13 additions & 27 deletions adafruit_sdcard.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,7 @@ class SDCard:
"""

def __init__(self, spi, cs, baudrate=1320000):
# This is the init baudrate.
# We create a second device with the target baudrate after card initialization.
# Create an SPIDevice running at a lower initialization baudrate first.
self._spi = spi_device.SPIDevice(spi, cs, baudrate=250000, extra_clocks=8)

self._cmdbuf = bytearray(6)
Expand All @@ -97,29 +96,21 @@ def __init__(self, spi, cs, baudrate=1320000):
# Card is byte addressing, set to 1 if addresses are per block
self._cdv = 512

# initialise the card and switch to high speed
self._init_card(baudrate)
# initialise the card
self._init_card(cs)

def _clock_card(self, cycles=8):
"""
Clock the bus a minimum of `cycles` with the chip select high.

:param int cycles: The minimum number of clock cycles to cycle the bus.
"""
while not self._spi.spi.try_lock():
pass
self._spi.spi.configure(baudrate=self._spi.baudrate)
self._spi.chip_select.value = True
# Create a new SPIDevice with the (probably) higher operating baudrate.
self._spi = spi_device.SPIDevice(spi, cs, baudrate=baudrate, extra_clocks=8)

self._single_byte[0] = 0xFF
for _ in range(cycles // 8 + 1):
self._spi.spi.write(self._single_byte)
self._spi.spi.unlock()

def _init_card(self, baudrate):
def _init_card(self, chip_select):
"""Initialize the card in SPI mode."""
# clock card at least cycles with cs high
self._clock_card(80)
# clock card at least 80 cycles with cs high
with self._spi as card:
# Force CS high.
chip_select.value = True
self._single_byte[0] = 0xFF
for _ in range(80 // 8 + 1):
card.write(self._single_byte)

with self._spi as card:
# CMD0: init card; should return _R1_IDLE_STATE (allow 5 attempts)
Expand Down Expand Up @@ -161,11 +152,6 @@ def _init_card(self, baudrate):
if self._cmd(card, 16, 512, 0x15) != 0:
raise OSError("can't set 512 block size")

# set to high data rate now that it's initialised
self._spi = spi_device.SPIDevice(
self._spi.spi, self._spi.chip_select, baudrate=baudrate, extra_clocks=8
)

def _init_card_v1(self, card):
"""Initialize v1 SDCards which use byte addressing."""
for _ in range(_CMD_TIMEOUT):
Expand Down