(self, baudrate)
| 64 | self.spi.init(master, baudrate=baudrate, phase=0, polarity=0) |
| 65 | |
| 66 | def init_card(self, baudrate): |
| 67 | |
| 68 | # init CS pin |
| 69 | self.cs.init(self.cs.OUT, value=1) |
| 70 | |
| 71 | # init SPI bus; use low data rate for initialisation |
| 72 | self.init_spi(100000) |
| 73 | |
| 74 | # clock card at least 100 cycles with cs high |
| 75 | for i in range(16): |
| 76 | self.spi.write(b"\xff") |
| 77 | |
| 78 | # CMD0: init card; should return _R1_IDLE_STATE (allow 5 attempts) |
| 79 | for _ in range(5): |
| 80 | if self.cmd(0, 0, 0x95) == _R1_IDLE_STATE: |
| 81 | break |
| 82 | else: |
| 83 | raise OSError("no SD card") |
| 84 | |
| 85 | # CMD8: determine card version |
| 86 | r = self.cmd(8, 0x01AA, 0x87, 4) |
| 87 | if r == _R1_IDLE_STATE: |
| 88 | self.init_card_v2() |
| 89 | elif r == (_R1_IDLE_STATE | _R1_ILLEGAL_COMMAND): |
| 90 | self.init_card_v1() |
| 91 | else: |
| 92 | raise OSError("couldn't determine SD card version") |
| 93 | |
| 94 | # get the number of sectors |
| 95 | # CMD9: response R2 (R1 byte + 16-byte block read) |
| 96 | if self.cmd(9, 0, 0, 0, False) != 0: |
| 97 | raise OSError("no response from SD card") |
| 98 | csd = bytearray(16) |
| 99 | self.readinto(csd) |
| 100 | if csd[0] & 0xC0 == 0x40: # CSD version 2.0 |
| 101 | self.sectors = ((csd[8] << 8 | csd[9]) + 1) * 1024 |
| 102 | elif csd[0] & 0xC0 == 0x00: # CSD version 1.0 (old, <=2GB) |
| 103 | c_size = (csd[6] & 0b11) << 10 | csd[7] << 2 | csd[8] >> 6 |
| 104 | c_size_mult = (csd[9] & 0b11) << 1 | csd[10] >> 7 |
| 105 | read_bl_len = csd[5] & 0b1111 |
| 106 | capacity = (c_size + 1) * (2 ** (c_size_mult + 2)) * (2**read_bl_len) |
| 107 | self.sectors = capacity // 512 |
| 108 | else: |
| 109 | raise OSError("SD card CSD format not supported") |
| 110 | # print('sectors', self.sectors) |
| 111 | |
| 112 | # CMD16: set block length to 512 bytes |
| 113 | if self.cmd(16, 512, 0) != 0: |
| 114 | raise OSError("can't set 512 block size") |
| 115 | |
| 116 | # set to high data rate now that it's initialised |
| 117 | self.init_spi(baudrate) |
| 118 | |
| 119 | def init_card_v1(self): |
| 120 | for i in range(_CMD_TIMEOUT): |
no test coverage detected