-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Using SPI on the ESP32-Cam to access the SD card and expand GPIOs
The ESP32-Cam uses most of its GPIOs to manage the onboard camera, RAM and SD-card reader. If the SD-card is not required there are a number of free GPIOs however if the SD-card is needed the number of available GPIOs is very limited.
Most SD-cards can be operated in three modes:
- 4 bit SD mode = uses 6 pins and is supported by the SD_MMC library by default SD_MMC.begin("/sdcard", false)
- 1 bit SD mode = uses 3 pins and is also supported by the SD_MMC library SD_MMC.begin("/sdcard", true);
- SPI mode = uses 4 pins and is supported by the SPI and SD libraries but not SD_MMC
In 4-bit SD mode there are no properly free GPIOs In 1-bit SD mode there are three free GPIOs (GPIO12, GPIO13, GPIO4) In SPI mode there are 2 free GPIOs (GPIO12, GPIO4)
NB GPIO4 is also the flashlight so although it can be used it has unwanted side effects
Under SPI it is possible to connect multiple slave SPI devices to the same SPI master bus. Each device then requires a dedicated GPIO to control its Chip Select (CS) The SD-card reader on the ESP32 is already hardwired for SPI as follows:
- CS = GPIO13
- MOSI = GPIO15
- CLK = GPIO14
- MISO = GPIO2
MCP 23S08 is an SPI I/O expander chip with 8 GPIOs while MCP23S17 has 16 GPIOs.
MCP23SXX will run at 5v but as SD-cards will not it is probably better to run it (and hence the SPI bus) at 3.3V. So a separate 3.3v low dropout regulator connected to the ESP32Cam 5v supply and powering the MCP23SXX (pin 18) is prudent.
Wiring
If GPIO12 is allocated as its CS the necessary connections are:
- ESP32CAM : MCP23SXX
- GPIO12 : pin 7 CS
- GPIO15 : pin 2 MOSI
- GPIO14 : pin 1 CLK
- GPIO2 : pin 3 MISO
- ______ : pin 4 A1 to Gnd
- ______ : pin 5 A0 to Gnd
- ______ : pin 6 RST to +3.3v
Attach an LED and a 120ohm resistor between each MCP23SXX GPIO and ground to see the example code working
Notes on the code
As the SPI pins in use are not the same as the default pins for either VSPI or HSPI the sketch needs to specify the SPI pins required explicitly but this can be done when initialising the default SPI object in setup(). It is not necessary to create new SPI objects.
As GPIO4 is not used to drive the SD-card it can be properly controlled so the flashlight only comes on when required. To do this it needs to be initialised to pinMode(OUTPUT) then digitalWrite(LOW) will turn it off. If left as INPUT the flashlight stays on but not at full brightness.
Finally, both the SD object that manages the SD-card and the Adafruit_MCP23S08 object that manages the I/O expander can be initialised in setup() with their allocated CS pins (SD.begin(SD_CS) and io.begin_SPI(IO_CS) and they will then assert and de-assert CS on each side of any device commands automatically so this does not need to be done in the sketch.
This work is licensed under the Creative Commons Attribution 4.0 International License.