def __init__(self, spi, xgcs, mcs):
     self._mag_device = spi_device.SPIDevice(
         spi, mcs, baudrate=200000, phase=1, polarity=1
     )
     self._xg_device = spi_device.SPIDevice(
         spi, xgcs, baudrate=200000, phase=1, polarity=1
     )
     super().__init__()
 def __init__(self, spi, xmcs, gcs):
     gcs.direction = Direction.OUTPUT
     gcs.value = True
     xmcs.direction = Direction.OUTPUT
     xmcs.value = True
     self._gyro_device = spi_device.SPIDevice(spi, gcs)
     self._xm_device = spi_device.SPIDevice(spi, xmcs)
     super().__init__()
    def __init__(self,
                 spi,
                 cs,
                 reset,
                 busy,
                 *,
                 preamble_length=8,
                 baudrate=1500000,
                 debug=False):
        # self._device = spidev.SPIDevice(spi, cs, baudrate=baudrate, polarity=0, phase=0)
        self._device = spidev.SPIDevice(spi, cs, polarity=0, phase=0)
        self._reset = reset
        self._reset.switch_to_input(pull=digitalio.Pull.UP)
        self._busy = busy
        self._busy.switch_to_input()
        self.packet_type = _PACKET_TYPE_GFSK  # default
        self._debug = debug
        self._set_ranging = False
        self._ranging = False
        self._status = 0

        self.reset()
        self._busywait()

        self.clear_Irq_Status()
        self.set_Regulator_Mode()
        self.set_Packet_Type()  # default LoRa
        self.set_Standby('STDBY_RC')
        self.set_Modulation_Params()
        self.set_Packet_Params(pktParam3=0x05)
        self.set_RF_Freq()  # 2.4GHz
        self.set_Buffer_Base_Address()
        self.set_Tx_Param()  # power=13dBm,rampTime=20us
        print('Radio Initialized')
    def __init__(self, spi, cs, *, baudrate=100000, int1=None, int2=None):
        from adafruit_bus_device import (  # pylint: disable=import-outside-toplevel
            spi_device, )

        self._spi = spi_device.SPIDevice(spi, cs, baudrate=baudrate)
        self._buffer = bytearray(6)
        super().__init__(int1=int1, int2=int2)
Example #5
0
 def __init__(self,
              spi,
              cs,
              rst=None,
              width=800,
              height=480,
              baudrate=6000000,
              polarity=0,
              phase=0):
     """
     :param SPI spi: The spi peripheral to use
     :param DigitalInOut cs: The chip-select pin to use (sometimes labeled "SS")
     :param DigitalInOut rst: (optional) The reset pin if it exists (default=None)
     :param int width: (optional) The width of the display in pixels (default=800)
     :param int height: (optional) The height of the display in pixels (default=480)
     :param int baudrate: (optional) The spi speed (default=6000000)
     :param int phase: (optional) The spi phase (default=0)
     :param int polarity: (optional) The spi polarity (default=0)
     """
     self.spi_device = spi_device.SPIDevice(spi,
                                            cs,
                                            baudrate=baudrate,
                                            polarity=polarity,
                                            phase=phase)
     self.width = width
     self.height = height
     self._mode = None
     self._tpin = None
     self.rst = rst
     if self.rst:
         self.rst.switch_to_output(value=0)
         self.reset()
     if self.read_reg(0) == 0x75:
         return
     self._adc_clk = reg.TPCR0_ADCCLK_DIV16
Example #6
0
    def __init__(self,
                 spi,
                 dc,
                 cs,
                 rst=None,
                 hardware_width=1,
                 hardware_height=1,
                 baudrate=12000000,
                 polarity=0,
                 phase=0,
                 x_offset=0,
                 y_offset=0):

        #spi device
        self.spi_device = spi_device.SPIDevice(spi,
                                               cs,
                                               baudrate=baudrate,
                                               polarity=polarity,
                                               phase=phase)
        self.dc_pin = dc
        self.rst = rst
        self.dc_pin.switch_to_output(value=0)
        if self.rst:
            self.rst.switch_to_output(value=0)
            self.reset()

        #disp device
        super().__init__(hardware_width,
                         hardware_height,
                         x_offset=x_offset,
                         y_offset=y_offset)
Example #7
0
    def __init__(self,
                 spi,
                 dc_pin,
                 cs_pin,
                 reset_pin=None,
                 *,
                 contrast=80,
                 bias=4,
                 baudrate=1000000):
        self._dc_pin = dc_pin
        dc_pin.switch_to_output(value=False)

        self.spi_device = spi_device.SPIDevice(spi, cs_pin, baudrate=baudrate)

        self._reset_pin = reset_pin
        if reset_pin:
            reset_pin.switch_to_output(value=True)

        self.buffer = bytearray((_LCDHEIGHT // 8) * _LCDWIDTH)
        super().__init__(self.buffer, _LCDWIDTH, _LCDHEIGHT)

        self._contrast = None
        self._bias = None
        self._invert = False

        self.reset()
        # Set LCD bias.
        self.bias = bias
        self.contrast = contrast
Example #8
0
 def __init__(self,
              spi,
              dc,
              cs,
              rst=None,
              width=1,
              height=1,
              baudrate=12000000,
              polarity=0,
              phase=0,
              *,
              x_offset=0,
              y_offset=0):
     self.spi_device = spi_device.SPIDevice(spi,
                                            cs,
                                            baudrate=baudrate,
                                            polarity=polarity,
                                            phase=phase)
     self.dc_pin = dc
     self.rst = rst
     self.dc_pin.switch_to_output(value=0)
     if self.rst:
         self.rst.switch_to_output(value=0)
         self.reset()
     self._X_START = x_offset  # pylint: disable=invalid-name
     self._Y_START = y_offset  # pylint: disable=invalid-name
     super().__init__(width, height)
Example #9
0
 def __init__(self,
              spi,
              cs,
              reset,
              frequency,
              *,
              preamble_length=8,
              high_power=True,
              baudrate=5000000):
     self.high_power = high_power
     # Device support SPI mode 0 (polarity & phase = 0) up to a max of 10mhz.
     # Set Default Baudrate to 5MHz to avoid problems
     self._device = spi_device.SPIDevice(spi,
                                         cs,
                                         baudrate=baudrate,
                                         polarity=0,
                                         phase=0)
     # Setup reset as a digital input (default state for reset line according
     # to the datasheet).  This line is pulled low as an output quickly to
     # trigger a reset.  Note that reset MUST be done like this and set as
     # a high impedence input or else the chip cannot change modes (trust me!).
     self._reset = reset
     self._reset.switch_to_input(pull=digitalio.Pull.UP)
     self.reset()
     # No device type check!  Catch an error from the very first request and
     # throw a nicer message to indicate possible wiring problems.
     try:
         # Set sleep mode, wait 10s and confirm in sleep mode (basic device check).
         # Also set long range mode (LoRa mode) as it can only be done in sleep.
         self.sleep()
         self.long_range_mode = True
         self._write_u8(_RH_RF95_REG_01_OP_MODE, 0b10001000)
         time.sleep(0.01)
         val = self._read_u8(_RH_RF95_REG_01_OP_MODE)
         print('op mode: {0}'.format(bin(val)))
         if self.operation_mode != SLEEP_MODE or not self.long_range_mode:
             raise RuntimeError(
                 'Failed to configure radio for LoRa mode, check wiring!')
     except OSError:
         raise RuntimeError(
             'Failed to communicate with radio, check wiring!')
     # clear default setting for access to LF registers if frequency > 525MHz
     if frequency > 525:
         self.low_frequency_mode = 0
     # Setup entire 256 byte FIFO
     self._write_u8(_RH_RF95_REG_0E_FIFO_TX_BASE_ADDR, 0x00)
     self._write_u8(_RH_RF95_REG_0F_FIFO_RX_BASE_ADDR, 0x00)
     # Set mode idle
     self.idle()
     # Set modem config to RadioHead compatible Bw125Cr45Sf128 mode.
     # Note no sync word is set for LoRa mode either!
     self._write_u8(_RH_RF95_REG_1D_MODEM_CONFIG1, 0x72)  # Fei msb?
     self._write_u8(_RH_RF95_REG_1E_MODEM_CONFIG2, 0x74)  # Fei lsb?
     self._write_u8(_RH_RF95_REG_26_MODEM_CONFIG3, 0x00)  # Preamble lsb?
     # Set preamble length (default 8 bytes to match radiohead).
     self.preamble_length = preamble_length
     # Set frequency
     self.frequency_mhz = frequency
     # Set TX power to low defaut, 13 dB.
     self.tx_power = 13
Example #10
0
    def __init__(self,
                 width,
                 height,
                 spi,
                 dc,
                 reset,
                 cs,
                 *,
                 external_vcc=False,
                 baudrate=8000000,
                 polarity=0,
                 phase=0,
                 page_addressing=False):
        self.page_addressing = page_addressing
        if self.page_addressing:
            raise NotImplementedError(
                "Page addressing mode with SPI has not yet been implemented.")

        self.rate = 10 * 1024 * 1024
        dc.switch_to_output(value=0)
        self.spi_device = spi_device.SPIDevice(spi,
                                               cs,
                                               baudrate=baudrate,
                                               polarity=polarity,
                                               phase=phase)
        self.dc_pin = dc
        self.buffer = bytearray((height // 8) * width)
        super().__init__(
            memoryview(self.buffer),
            width,
            height,
            external_vcc=external_vcc,
            reset=reset,
            page_addressing=self.page_addressing,
        )
Example #11
0
 def __init__(self, spi, cs, baudrate=1000000): # DRV8305 supports up to 10 MHz
     import adafruit_bus_device.spi_device as spi_device  # pylint: disable=import-outside-toplevel
     self._spi = spi_device.SPIDevice(spi, chip_select=cs, polarity=0, phase=1) # avoid overwriting polarity & phase
     self._spi.chip_select.value = True # idle high
     # ^ adafruit_bus_device.spi_device.__init__ switches it to an output with the arg value=True, but I'm seeing it low for ~224 ms on the scope after init if I don't add this
     self._c = _DRV8305_SPI_Word()
     self._r = _DRV8305_SPI_Word()
Example #12
0
    def __init__(self,
                 width,
                 height,
                 spi,
                 cs,
                 *,
                 baudrate=8000000,
                 polarity=0,
                 phase=0):

        self._chip_select = cs
        self._chip_select.direction = digitalio.Direction.OUTPUT

        self._spi_device = spi_device.SPIDevice(spi,
                                                cs,
                                                baudrate=baudrate,
                                                polarity=polarity,
                                                phase=phase)

        self._buffer = bytearray((height // 8) * width)
        self.framebuf = framebuf.FrameBuffer1(self._buffer, width, height)

        self.width = width
        self.height = height

        self.init_display()
Example #13
0
 def __init__(self,
              spi,
              cs,
              *,
              rtd_nominal=100,
              ref_resistor=430.0,
              wires=2):
     self.rtd_nominal = rtd_nominal
     self.ref_resistor = ref_resistor
     self._device = spi_device.SPIDevice(spi,
                                         cs,
                                         baudrate=500000,
                                         polarity=0,
                                         phase=1)
     # Set wire config register based on the number of wires specified.
     if wires not in (2, 3, 4):
         raise ValueError('Wires must be a value of 2, 3, or 4!')
     config = self._read_u8(_MAX31865_CONFIG_REG)
     if wires == 3:
         config |= _MAX31865_CONFIG_3WIRE
     else:
         # 2 or 4 wire
         config &= ~_MAX31865_CONFIG_3WIRE
     self._write_u8(_MAX31865_CONFIG_REG, config)
     # Default to no bias and no auto conversion.
     self.bias = False
     self.auto_convert = False
Example #14
0
 def __init__(self,
              width,
              height,
              spi,
              dc,
              reset,
              cs,
              *,
              external_vcc=False,
              baudrate=8000000,
              polarity=0,
              phase=0):
     self.rate = 10 * 1024 * 1024
     dc.switch_to_output(value=0)
     self.spi_device = spi_device.SPIDevice(spi,
                                            cs,
                                            baudrate=baudrate,
                                            polarity=polarity,
                                            phase=phase)
     self.dc_pin = dc
     self.buffer = bytearray((height // 8) * width)
     super().__init__(memoryview(self.buffer),
                      width,
                      height,
                      external_vcc=external_vcc,
                      reset=reset)
Example #15
0
 def __init__(self, spi, cs):
     import adafruit_bus_device.spi_device as spi_device
     self._spi = spi_device.SPIDevice(spi, cs)
     # toggle CS low/high to put BMP3XX in SPI mode
     with self._spi:
         time.sleep(0.001)
     super().__init__()
    def __init__(self, spi, cs, baudrate=100000, debug=False, *, refresh_rate=10):
        from adafruit_bus_device import (  # pylint: disable=import-outside-toplevel
            spi_device,
        )

        self._spi = spi_device.SPIDevice(spi, cs, baudrate=baudrate)
        self._debug = debug
        super().__init__(refresh_rate=refresh_rate)
Example #17
0
    def __init__(  # pylint: disable=too-many-arguments
            self,
            spi,
            cs,
            baudrate=1000000,
            calibration=None,
            size=None,
            disp_rotation=0,
            touch_flip=(False, False),
    ):

        self._calib = calibration
        self._disp_size = size
        self._disp_rotation = disp_rotation
        self._touch_flip = touch_flip

        # Check the touchscreen calibration and display size kwargs.
        if not self._calib:
            self._calib = ((0, 4095), (0, 4095))
        if not self._disp_size:
            self._disp_size = (4095, 4095)

        if self._disp_rotation not in (0, 90, 180, 270):
            raise ValueError(
                "Display rotation value must be 0, 90, 180, or 270")

        # Check that the STMPE610 was found.
        import adafruit_bus_device.spi_device as spidev  # pylint: disable=import-outside-toplevel

        self._spi = spidev.SPIDevice(spi, cs, baudrate=baudrate)
        # Check device version.
        version = self.get_version
        if _STMPE_VERSION != version:
            # If it fails try SPI MODE 1  -- that is what Arduino does
            self._spi = spidev.SPIDevice(spi,
                                         cs,
                                         baudrate=baudrate,
                                         polarity=0,
                                         phase=1)
            version = self.get_version
            if _STMPE_VERSION != version:
                raise RuntimeError(
                    "Failed to find STMPE610 controller! Chip Version 0x%x. "
                    "If you are using the breakout, verify you are in SPI mode."
                    % version)
        super().__init__()
Example #18
0
 def __init__(self, spi, cs, reset, frequency, *, sync_word=b'\x2D\xD4',
              preamble_length=4, encryption_key=None, high_power=True, baudrate=5000000):
     self._tx_power = 13
     self.high_power = high_power
     # Device support SPI mode 0 (polarity & phase = 0) up to a max of 10mhz.
     self._device = spidev.SPIDevice(spi, cs, baudrate=baudrate,
                                     polarity=0, phase=0)
     # Setup reset as a digital output that's low.
     self._reset = reset
     self._reset.switch_to_output(value=False)
     # Reset the chip.
     self.reset()
     # Check the version of the chip.
     version = self._read_u8(_REG_VERSION)
     if version != 0x24:
         raise RuntimeError('Failed to find RFM69 with expected version, check wiring!')
     # Enter idle state.
     self.idle()
     # Setup the chip in a similar way to the RadioHead RFM69 library.
     # Set FIFO TX condition to not empty and the default FIFO threshold
     # to 15.
     self._write_u8(_REG_FIFO_THRESH, 0b10001111)
     # Configure low beta off.
     self._write_u8(_REG_TEST_DAGC, 0x30)
     # Disable boost.
     self._write_u8(_REG_TEST_PA1, _TEST_PA1_NORMAL)
     self._write_u8(_REG_TEST_PA2, _TEST_PA2_NORMAL)
     # Set the syncronization word.
     self.sync_word = sync_word
     # Configure modulation for RadioHead library GFSK_Rb250Fd250 mode
     # by default.  Users with advanced knowledge can manually reconfigure
     # for any other mode (consulting the datasheet is absolutely
     # necessary!).
     self.data_mode = 0b00              # Packet mode
     self.modulation_type = 0b00        # FSK modulation
     self.modulation_shaping = 0b01     # Gaussian filter, BT=1.0
     self.bitrate = 250000              # 250kbs
     self.frequency_deviation = 250000  # 250khz
     self.rx_bw_dcc_freq = 0b111        # RxBw register = 0xE0
     self.rx_bw_mantissa = 0b00
     self.rx_bw_exponent = 0b000
     self.afc_bw_dcc_freq = 0b111       # AfcBw register = 0xE0
     self.afc_bw_mantissa = 0b00
     self.afc_bw_exponent = 0b000
     self.packet_format = 1             # Variable length.
     self.dc_free = 0b10                # Whitening
     self.crc_on = 1                    # CRC enabled
     self.crc_auto_clear = 0            # Clear FIFO on CRC fail
     self.address_filtering = 0b00      # No address filtering
     # Set the preamble length.
     self.preamble_length = preamble_length
     # Set frequency.
     self.frequency_mhz = frequency
     # Set encryption key.
     self.encryption_key = encryption_key
     # Set transmit power to 13 dBm, a safe value any module supports.
     self.tx_power = 13
Example #19
0
 def __init__(self, cs_pin, spi):
     # Handle hardware SPI
     self._spi = spi_device.SPIDevice(spi, cs_pin, baudrate=8000000)
     self.spi_device = spi
     self.cs_pin = cs_pin
     self._buf = bytearray(3)
     self._buf[0] = Adafruit_MCP_SRAM.SRAM_WRSR
     self._buf[1] = 0x43
     with self._spi as spidev:
         spidev.write(self._buf, end=2)  # pylint: disable=no-member
Example #20
0
 def __init__(self,
              spi_busio,
              cs,
              rng=L3DS20_RANGE_250DPS,
              baudrate=100000):
     import adafruit_bus_device.spi_device as spi_device
     self._spi = spi_device.SPIDevice(spi_busio, cs, baudrate=baudrate)
     self._spi_bytearray1 = bytearray(1)
     self._spi_bytearray6 = bytearray(6)
     super().__init__(rng)
    def __init__(self,
                 spi_bus,
                 cs_pin,
                 *,
                 baudrate: int = 250000,
                 loopback: bool = False,
                 silent: bool = False,
                 auto_restart: bool = False,
                 debug: bool = False):
        """A common shared-bus protocol.

        :param ~busio.SPI spi: The SPI bus used to communicate with the MCP2515
        :param ~digitalio.DigitalInOut cs_pin:  SPI bus enable pin
        :param int baudrate: The bit rate of the bus in Hz, using a 16Mhz crystal. All devices on\
            the bus must agree on this value. Defaults to 250000.
        :param bool loopback: Receive only packets sent from this device, and send only to this\
        device. Requires that `silent` is also set to `True`, but only prevents transmission to\
        other devices. Otherwise the send/receive behavior is normal.
        :param bool silent: When `True` the controller does not transmit and all messages are\
        received, ignoring errors and filters. This mode can be used to “sniff” a CAN bus without\
        interfering. Defaults to `False`.
        :param bool auto_restart: **Not supported by hardware. An `AttributeError` will be raised\
        if `auto_restart` is set to `True`** If `True`, will restart communications after entering\
        bus-off state. Defaults to `False`.

        :param bool debug: If `True`, will enable printing debug information. Defaults to `False`.
        """

        if loopback and not silent:
            raise AttributeError("Loopback mode requires silent to be set")
        if auto_restart:
            raise AttributeError("`auto-restart` is not supported by hardware")

        self._auto_restart = auto_restart
        self._debug = debug
        self._bus_device_obj = spi_device.SPIDevice(spi_bus, cs_pin)
        self._cs_pin = cs_pin
        self._buffer = bytearray(20)
        self._id_buffer = bytearray(4)
        self._unread_message_queue = []
        self._timer = Timer()
        self._tx_buffers = []
        self._rx0_overflow = False
        self._rx1_overflow = False
        self._masks_in_use = []
        self._filters_in_use = [[], []]
        self._mode = None
        self._bus_state = BusState.ERROR_ACTIVE
        self._baudrate = baudrate
        self._loopback = loopback
        self._silent = silent
        self._baudrate = baudrate

        self._init_buffers()
        self.initialize()
 def __init__(self,
              spi,
              cs,
              baudrate=100000,
              debug=False,
              *,
              refresh_rate=10):
     from adafruit_bus_device import spi_device
     self._spi = spi_device.SPIDevice(spi, cs, baudrate=baudrate)
     self._debug = debug
     super().__init__(refresh_rate=refresh_rate)
Example #23
0
 def __init__(self, spi, dc, cs, rst=None, width=1, height=1, baudrate=1000000,
              polarity=0, phase=0):
     self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate,
                                            polarity=polarity, phase=phase)
     self.dc_pin = dc
     self.rst = rst
     self.dc_pin.switch_to_output(value=0)
     if self.rst:
         self.rst.switch_to_output(value=0)
         self.reset()
     super().__init__(width, height)
 def __init__(self, width, height, spi, a0, reset, cs, *,
              external_vcc=False, baudrate=20000000, polarity=0, phase=0):
     self.rate = 10 * 1024 * 1024
     a0.switch_to_output(value=0)
     self.spi_device = spi_device.SPIDevice(spi, cs, baudrate=baudrate,
                                            polarity=polarity, phase=phase)
     self.a0_pin = a0
     # self.buffer = bytearray(height * width)
     self.buffer = bytearray((height // 8) * width)
     framebuffer = framebuf.FrameBuffer1(self.buffer, width, height)
     super().__init__(framebuffer, width, height, external_vcc, reset)
 def __init__(self, spi, cs, baudrate=1000000):
     """
     Check the STMPE610 was found,Default clock rate 1000000 - can be changed with 'baudrate'
     """
     import adafruit_bus_device.spi_device as spidev
     self._spi = spidev.SPIDevice(spi, cs, baudrate=baudrate)
     # Check device version.
     version = self.get_version
     if _STMPE_VERSION != version:
         # if it fails try SPI MODE 1  -- that is what Arduino does
         self._spi = spidev.SPIDevice(spi,
                                      cs,
                                      baudrate=baudrate,
                                      polarity=0,
                                      phase=1)
         version = self.get_version
         if _STMPE_VERSION != version:
             raise RuntimeError(
                 'Failed to find STMPE610! Chip Version 0x%x' % version)
     super().__init__()
Example #26
0
    def __init__(self, spi, cs, baudrate=1320000):
        # 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)
        self._single_byte = bytearray(1)

        # Card is byte addressing, set to 1 if addresses are per block
        self._cdv = 512

        # initialise the card
        self._init_card(cs)

        # Create a new SPIDevice with the (probably) higher operating baudrate.
        self._spi = spi_device.SPIDevice(spi,
                                         cs,
                                         baudrate=baudrate,
                                         extra_clocks=8)
    def __init__(self, spi, cs):
        # This is the init baudrate. We create a second device for high speed.
        self._spi = spi_device.SPIDevice(spi, cs, baudrate=250000, extra_clocks=8)

        self._cmdbuf = bytearray(6)
        self._single_byte = bytearray(1)

        # Card is byte addressing, set to 1 if addresses are per block
        self._cdv = 512

        # initialise the card
        self._init_card()
 def __init__(
     self,
     bus_device: Union[I2C, SPI],
     address: int,
     chip_select: Optional[digitalio.DigitalInOut] = None,
     baudrate: int = 100000,
 ) -> None:
     if chip_select is None:
         self._device = i2c_device.I2CDevice(bus_device, address)
     else:
         self._device = spi_device.SPIDevice(bus_device,
                                             chip_select,
                                             baudrate=baudrate)
Example #29
0
    def __init__(self, spi, cs, baudrate=1320000):
        # This is the init baudrate.
        # We create a second device with the target baudrate after card initialization.
        self._spi = spi_device.SPIDevice(spi, cs, baudrate=250000, extra_clocks=8)

        self._cmdbuf = bytearray(6)
        self._single_byte = bytearray(1)

        # 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)
Example #30
0
    def _init_card(self, baudrate):
        """Initialize the card in SPI mode."""
        # clock card at least cycles with cs high
        self._clock_card(80)

        with self._spi as card:
            # CMD0: init card; should return _R1_IDLE_STATE (allow 5 attempts)
            for _ in range(5):
                if self._cmd(card, 0, 0, 0x95) == _R1_IDLE_STATE:
                    break
            else:
                raise OSError("no SD card")

            # CMD8: determine card version
            rb7 = bytearray(4)
            r = self._cmd(card, 8, 0x01AA, 0x87, rb7, data_block=False)
            if r == _R1_IDLE_STATE:
                self._init_card_v2(card)
            elif r == (_R1_IDLE_STATE | _R1_ILLEGAL_COMMAND):
                self._init_card_v1(card)
            else:
                raise OSError("couldn't determine SD card version")

            # get the number of sectors
            # CMD9: response R2 (R1 byte + 16-byte block read)
            csd = bytearray(16)
            if self._cmd(card, 9, 0, 0xAF, response_buf=csd) != 0:
                raise OSError("no response from SD card")
            # self.readinto(csd)
            csd_version = (csd[0] & 0xC0) >> 6
            if csd_version >= 2:
                raise OSError("SD card CSD format not supported")

            if csd_version == 1:
                self._sectors = ((csd[8] << 8 | csd[9]) + 1) * 1024
            else:
                block_length = 2**(csd[5] & 0xF)
                c_size = ((csd[6] & 0x3) << 10) | (csd[7] << 2) | (
                    (csd[8] & 0xC) >> 6)
                mult = 2**(((csd[9] & 0x3) << 1 | (csd[10] & 0x80) >> 7) + 2)
                self._sectors = block_length // 512 * mult * (c_size + 1)

            # CMD16: set block length to 512 bytes
            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)