Skip to content

Commit b069204

Browse files
authored
Merge pull request #43 from dhalbert/simplify-use-of-spidevice-42
Make compatible with native adafruit_bus_device
2 parents e7c6a46 + bcc5b95 commit b069204

File tree

1 file changed

+13
-27
lines changed

1 file changed

+13
-27
lines changed

adafruit_sdcard.py

Lines changed: 13 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,7 @@ class SDCard:
8787
"""
8888

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

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

100-
# initialise the card and switch to high speed
101-
self._init_card(baudrate)
99+
# initialise the card
100+
self._init_card(cs)
102101

103-
def _clock_card(self, cycles=8):
104-
"""
105-
Clock the bus a minimum of `cycles` with the chip select high.
106-
107-
:param int cycles: The minimum number of clock cycles to cycle the bus.
108-
"""
109-
while not self._spi.spi.try_lock():
110-
pass
111-
self._spi.spi.configure(baudrate=self._spi.baudrate)
112-
self._spi.chip_select.value = True
102+
# Create a new SPIDevice with the (probably) higher operating baudrate.
103+
self._spi = spi_device.SPIDevice(spi, cs, baudrate=baudrate, extra_clocks=8)
113104

114-
self._single_byte[0] = 0xFF
115-
for _ in range(cycles // 8 + 1):
116-
self._spi.spi.write(self._single_byte)
117-
self._spi.spi.unlock()
118-
119-
def _init_card(self, baudrate):
105+
def _init_card(self, chip_select):
120106
"""Initialize the card in SPI mode."""
121-
# clock card at least cycles with cs high
122-
self._clock_card(80)
107+
# clock card at least 80 cycles with cs high
108+
with self._spi as card:
109+
# Force CS high.
110+
chip_select.value = True
111+
self._single_byte[0] = 0xFF
112+
for _ in range(80 // 8 + 1):
113+
card.write(self._single_byte)
123114

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

164-
# set to high data rate now that it's initialised
165-
self._spi = spi_device.SPIDevice(
166-
self._spi.spi, self._spi.chip_select, baudrate=baudrate, extra_clocks=8
167-
)
168-
169155
def _init_card_v1(self, card):
170156
"""Initialize v1 SDCards which use byte addressing."""
171157
for _ in range(_CMD_TIMEOUT):

0 commit comments

Comments
 (0)