The Arduino core for the esp32 chip includes two libraries to communicate with SD cards:

The reason is because – as explained in the datasheet – the esp32 chip features a SD/SDIO/MMC host controller, in addition to the “generic” SPI one.

If you include in your sketch the SD_MMC library, you’ll use that dedicated host controller, while if you include the SD library you’ll use the SPI controller.

The esp32-s2 chip does not include the MMC host controller: to interface that chip with an SD card it’s therefore necessary to use the SPI controller and the SD library.

Both the libraries define, for the different signals, some standard pins.

One of the key features of the esp32 chip, however, is the possibility to remap the peripherals on different pins. In this short tutorial I’ll explain how to tell the SD library which pins you want to use.

The chip includes two SPI interfaces:

  • HSPI
  • VSPI

First you have to define an instance of the SPIClass class, specifying which interface you want to use:

vspi = new SPIClass(VSPI);
hspi = new SPIClass(HSPI);

The begin method allows to define which pins correspond to the different SPI signals:

vspi->begin(SCLK, MISO, MOSI, SS);

If, for example, you want to use the HSPI interface with pins 2-13-14-15 write the following code:

#define HSPI_MISO   2
#define HSPI_MOSI   15
#define HSPI_SCLK   14
#define HSPI_SS     13

SPIClass *spi = NULL;

spi = new SPIClass(HSPI);

Finally, tell the SD library which SPIClass instance it has to use and which is the chip select pin:

SD.begin(HSPI_SS, *spi)

Now you can call the library methods as usual, for example:

uint8_t cardType = SD.cardType();