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.
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:
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); spi->begin(HSPI_SCLK, HSPI_MISO, HSPI_MOSI, HSPI_SS);
Finally, tell the SD library which SPIClass instance it has to use and which is the chip select pin:
Now you can call the library methods as usual, for example:
uint8_t cardType = SD.cardType();