NodeMCU : Interfacing SD Card with ESP8266

I have written many blogs on NodeMCU , but SD card example was missing. in this blog we will see how to mount SD card in NodeMCU filesystem, access files from SD card using NodeMCU’s file API.

We will be using SD card in SPI mode, first we need to connect the SD card breakout board with NodeMCU.

Connecting SD card board to NodeMCU :

You don’t need any level shifter, you can directly connect from SD card breakout to NodeMCU, if your breakout board already has a level shifter supply 3v3 for VCC  pin of breakout board. Connect SD card board to NodeMCU according to following connections

NodeMCU SD card connections
NodeMCU SD card connections
nodemcu_sdcard
nodemcu_sdcard

By default FatFS module is disabled in nodemcu firmware, you need to build the firmware with FatFS support your self, or you can use the online build tool

Goto nodemcu-build.com , build firmware according to your needs, don’t forget to check the FatFS support at the bottom of the page

Load the new firmware and enter the following commands in the serial console, it will list the files in root directory of the SD card.

spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, 8, 8);
vol = file.mount("/SD0", 8);
file.chdir('/SD0');
l = file.list();
for k,v in pairs(l) do
 print("name:"..k..", size:"..v)
end

We can open a file using file.open(‘/SD0/filename’), you can check out the file API for list of functions available, following snippet will print the contents of the foo.txt  file

spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, 8, 8);
vol = file.mount("/SD0", 8);
file.open("/SD0/foo.txt")
print(file.read())
file.close()

if the file is too big, the nodemcu will reset itslef, you might need yield the control to the system in the read loop by calling tmr.wdclr()

13 Comments

Add a Comment

Your email address will not be published. Required fields are marked *