Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // SPI peripheral setup
- Baudrate: DIV128 (HSI 16MHz -> 125kHz)
- Clock polarity: Low on idle
- Clock phase: First transition
- DDF: 8 bits
- FF: MSB first
- SSI and SSM: enabled
- Frame std: Motorola
- Role: Master
- // This is the init sequence
- delay_ms(1000);
- cs_high();
- for (u32 i = 0; i < 30; ++i)
- {
- WAIT_UNTIL(spi_is_flag_set(SPI1, SPI_FLAG_TX_BUF_EMPTY));
- spi_data_write(SPI1, 0xff);
- }
- u8 cmd0[] = {
- 0x40, 0x00, 0x00, 0x00, 0x00, 0x95
- };
- cs_low();
- send_spi_cmd(cmd0);
- u8 r1 = get_spi_resp();
- cs_high();
- if (r1 != 0x01)
- {
- while (1);
- }
- u8 cmd8[] = {
- 0x48, 0x00, 0x00, 0x01, 0xaa, 0x87
- };
- cs_low();
- send_spi_cmd(cmd8);
- r1 = get_spi_resp();
- u32 r7[4];
- for (u32 i = 0; i < 4; ++i)
- {
- spi_data_write(SPI1, 0xff);
- WAIT_UNTIL(spi_is_flag_set(SPI1, SPI_FLAG_RX_BUF_NOT_EMPTY));
- WAIT_UNTIL(spi_is_flag_set(SPI1, SPI_FLAG_BUSY) == 0);
- r7[i] = spi_data_read(SPI1);
- }
- cs_high();
- // r7 = 0x00, 0x00, 0x01, 0xaa
- u8 cmd58[] = { 0x7a, 0x00, 0x00, 0x00, 0x00, 0xfd };
- cs_low();
- send_spi_cmd(cmd58);
- r1 = get_spi_resp();
- u8 ocr[4];
- for (u32 i = 0; i < 4; ++i)
- {
- spi_data_write(SPI1, 0xff);
- WAIT_UNTIL(spi_is_flag_set(SPI1, SPI_FLAG_RX_BUF_NOT_EMPTY));
- WAIT_UNTIL(spi_is_flag_set(SPI1, SPI_FLAG_BUSY) == 0);
- ocr[i] = spi_data_read(SPI1);
- }
- cs_high();
- // OCR = 0x00, 0xff, 0x80, 0x00
- u8 cmd55[] = { 0x77, 0x0, 0x0, 0x0, 0x0, 0x65 };
- u8 acmd41[] = { 0x69, 0x00, 0x00, 0x00, 0x00, 0x5f };
- while (1)
- {
- cs_low();
- send_spi_cmd(cmd55);
- u8 cmd55_r = get_spi_resp();
- cs_high();
- if (cmd55_r != 0x01)
- {
- // Error
- break;
- }
- delay_ms(100);
- cs_low();
- send_spi_cmd(acmd41);
- u8 acmd41_r = get_spi_resp();
- cs_high();
- if (acmd41_r == 0)
- {
- // Card is ready
- break;
- }
- delay_ms(100);
- }
- // send_spi_cmd() and get_spi_resp()
- void
- send_spi_cmd(u8* cmd)
- {
- for (u32 i = 0; i < 6; ++i)
- {
- WAIT_UNTIL(spi_is_flag_set(SPI1, SPI_FLAG_TX_BUF_EMPTY));
- spi_data_write(SPI1, cmd[i]);
- WAIT_UNTIL(spi_is_flag_set(SPI1, SPI_FLAG_BUSY) == 0);
- WAIT_UNTIL(spi_is_flag_set(SPI1, SPI_FLAG_RX_BUF_NOT_EMPTY));
- (void) spi_data_read(SPI1);
- }
- }
- u8
- get_spi_resp(void)
- {
- while (1)
- {
- WAIT_UNTIL(spi_is_flag_set(SPI1, SPI_FLAG_TX_BUF_EMPTY));
- spi_data_write(SPI1, 0xff);
- WAIT_UNTIL(spi_is_flag_set(SPI1, SPI_FLAG_RX_BUF_NOT_EMPTY));
- u8 data = spi_data_read(SPI1);
- if ((data & 0x80) == 0)
- {
- return data;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment