ESP32 MicroPython Micro SD Card

This guide walks you through interfacing a Micro SD Card with the ESP32 using MicroPython. You will learn how to:

ESP32 MicroPython and Micro SD Card

Hardware Preparation

1×ESP-WROOM-32 Dev Module
1×Alternatively, ESP32 Uno-form board
1×Alternatively, ESP32 S3 Uno-form board
1×USB Cable Type-A to Type-C (for USB-A PC)
1×USB Cable Type-C to Type-C (for USB-C PC)
1×Micro SD Card
1×Micro SD Card Module
1×Jumper Wires
1×Breadboard
1×Optionally, MicroSD to SD Memory Card Adapter
1×Recommended: Screw Terminal Expansion Board for ESP32
1×Recommended: Breakout Expansion Board for ESP32
1×Recommended: Power Splitter for ESP32

Or you can buy the following kits:

1×DIYables ESP32 Starter Kit (ESP32 included)
1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

Overview of Micro SD Card Module

A Micro SD Card Module acts as an adapter that allows the ESP32 to communicate with a Micro SD Card via the SPI protocol. It serves as a connector between the microcontroller and the storage card.

Pinout

Micro SD Card Module Pinout

The Micro SD Card Module has 6 pins:

  • VCC pin: powers the module, connect to the ESP32's 5V output.
  • GND pin: ground reference, connect to the ESP32's GND.
  • MISO pin: (Master In Slave Out) data line from SD card to ESP32.
  • MOSI pin: (Master Out Slave In) data line from ESP32 to SD card.
  • SCK pin: SPI clock signal, connect to the ESP32's SCK.
  • SS pin: (Slave Select) chip select pin, assigned in the MicroPython code.

Preparation

  • Plug the Micro SD Card into a USB 3.0 SD Card Reader and connect it to your PC
  • Verify that the Micro SD Card uses FAT16 or FAT32 format (search online for instructions if needed)

Wiring Diagram

The wiring diagram between ESP32 MicroPython Micro SD Card Module

This image is created using Fritzing. Click to enlarge image

The wiring table below shows how to connect the Micro SD Card Module to the ESP32:

Micro SD Card Module ESP32
VCC 5V
GND GND
MISO GPIO19
MOSI GPIO23
SCK GPIO18
CS GPIO5

※ NOTE THAT:

If your shield (such as an Ethernet shield) already has a built-in Micro SD Card slot, you can skip the external module and simply insert the card directly into the shield.

ESP32 MicroPython - Opening and Creating a File on Micro SD Card

ESP32 MicroPython Code

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-micro-sd-card """ import machine import os import sdcard # Define SPI pins for the Micro SD Card module SPI_SCK_PIN = 18 # The ESP32 pin GPIO18 connected to SCK SPI_MOSI_PIN = 23 # The ESP32 pin GPIO23 connected to MOSI SPI_MISO_PIN = 19 # The ESP32 pin GPIO19 connected to MISO SPI_CS_PIN = 5 # The ESP32 pin GPIO5 connected to SS (CS) # Initialize SD card using SoftSPI and sdcard driver spi = machine.SoftSPI(baudrate=1000000, polarity=0, phase=0, sck=machine.Pin(SPI_SCK_PIN), mosi=machine.Pin(SPI_MOSI_PIN), miso=machine.Pin(SPI_MISO_PIN)) cs = machine.Pin(SPI_CS_PIN, machine.Pin.OUT) try: sd = sdcard.SDCard(spi, cs) os.mount(sd, "/sd") print("SD CARD INITIALIZED.") except Exception as e: print("SD CARD FAILED, OR NOT PRESENT!", e) raise SystemExit # Check if the file exists file_path = "/sd/esp32.txt" if file_path.replace("/sd/", "") not in os.listdir("/sd"): print("esp32.txt doesn't exist. Creating esp32.txt file...") # Create a new file by opening it and immediately closing it f = open(file_path, "w") f.close() # Recheck if file is created or not if file_path.replace("/sd/", "") in os.listdir("/sd"): print("esp32.txt exists on SD Card.") else: print("esp32.txt doesn't exist on SD Card.") os.umount("/sd")

Detailed Instructions

Here's instructions on how to set up and run your MicroPython code on the ESP32 using Thonny IDE:

  • Make sure Thonny IDE is installed on your computer.
  • Confirm that MicroPython firmware is loaded on your ESP32 board.
  • If this is your first time using an ESP32 with MicroPython, check out the ESP32 MicroPython Getting Started guide for step-by-step instructions.
  • Insert the Micro SD Card to the Micro SD Card module.
  • Do the wiring between the Micro SD Card module and ESP32 as the above wiring diagram.
  • Connect the ESP32 board to your computer with a USB cable.
  • Open Thonny IDE on your computer.
  • In Thonny IDE, go to Tools Options.
  • Under the Interpreter tab, choose MicroPython (ESP32) from the dropdown menu.
  • Make sure the correct port is selected. Thonny IDE usually detects it automatically, but you might need to select it manually (like COM3 on Windows or /dev/ttyACM0 on Linux).
  • Navigate to the Tools Manage packages on the Thonny IDE.
  • Search "sdcard", then find the sdcard library provided by micropython-lib.
  • Click on sdcard, then click Install button to install the SD card library.
ESP32 MicroPython SD Card library
  • Copy the provided MicroPython code and paste it into Thonny's editor.
  • Save the code to your ESP32 by:
    • Clicking the Save button or pressing Ctrl+S.
    • In the save dialog, choose MicroPython device.
    • Name the file main.py.
  • Click the green Run button (or press F5) to execute the script.
  • Check out the message in the Shell at the bottom of Thonny.
  • The result on the Shell for the first run
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot SD CARD INITIALIZED. esp32.txt doesn't exist. Creating esp32.txt file... esp32.txt exists on SD Card.
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡
  • The result on the Shell for the next runs
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot SD CARD INITIALIZED. esp32.txt exists on SD Card.
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡
  • Detach the Micro SD Card from the module
  • Insert the Micro SD Card to an USB SD Card reader
  • Connect the USB SD Card reader to the PC
  • Check if the file exists or not

ESP32 MicroPython - Writing and Reading Data on Micro SD Card

The following MicroPython code performs two operations:

  • Saves data into a file on the SD card
  • Reads the file content character-by-character and displays it in the Shell
""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-micro-sd-card """ import machine import os import sdcard # Define SPI pins for the Micro SD Card module SPI_SCK_PIN = 18 # The ESP32 pin GPIO18 connected to SCK SPI_MOSI_PIN = 23 # The ESP32 pin GPIO23 connected to MOSI SPI_MISO_PIN = 19 # The ESP32 pin GPIO19 connected to MISO SPI_CS_PIN = 5 # The ESP32 pin GPIO5 connected to SS (CS) # Initialize SD card using SoftSPI and sdcard driver spi = machine.SoftSPI(baudrate=1000000, polarity=0, phase=0, sck=machine.Pin(SPI_SCK_PIN), mosi=machine.Pin(SPI_MOSI_PIN), miso=machine.Pin(SPI_MISO_PIN)) cs = machine.Pin(SPI_CS_PIN, machine.Pin.OUT) try: sd = sdcard.SDCard(spi, cs) os.mount(sd, "/sd") print("SD CARD INITIALIZED.") except Exception as e: print("SD CARD FAILED, OR NOT PRESENT!", e) raise SystemExit file_path = "/sd/esp32.txt" # Open file for writing (append mode) try: f = open(file_path, "a") f.write("Created by newbiely.com\n") # write a line to esp32.txt f.write("Learn ESP32 and SD Card\n") # write another line to esp32.txt f.close() except Exception as e: print("SD Card: Issue encountered while attempting to open the file esp32.txt", e) # Open file for reading try: f = open(file_path, "r") while True: ch = f.read(1) # read characters one by one from Micro SD Card if not ch: break print(ch, end="") # print the character to the Shell f.close() except Exception as e: print("SD Card: Issue encountered while attempting to open the file esp32.txt", e) os.umount("/sd")
  • The Shell displays the file content:
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot Created by newbiely.com Learn ESP32 and SD Card
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡

※ NOTE THAT:

By default, new data is appended at the end of the file. If you restart the ESP32 using the same code, the text gets added again, so the Shell output will look like this:

Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot Created by newbiely.com Learn ESP32 and SD Card Created by newbiely.com Learn ESP32 and SD Card
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡

You can also remove the Micro SD Card from the module and view its contents on your PC (a USB SD Card reader is required)

ESP32 MicroPython - Reading a File Line by Line from Micro SD Card

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-micro-sd-card """ import machine import os import sdcard # Define SPI pins for the Micro SD Card module SPI_SCK_PIN = 18 # The ESP32 pin GPIO18 connected to SCK SPI_MOSI_PIN = 23 # The ESP32 pin GPIO23 connected to MOSI SPI_MISO_PIN = 19 # The ESP32 pin GPIO19 connected to MISO SPI_CS_PIN = 5 # The ESP32 pin GPIO5 connected to SS (CS) # Initialize SD card using SoftSPI and sdcard driver spi = machine.SoftSPI(baudrate=1000000, polarity=0, phase=0, sck=machine.Pin(SPI_SCK_PIN), mosi=machine.Pin(SPI_MOSI_PIN), miso=machine.Pin(SPI_MISO_PIN)) cs = machine.Pin(SPI_CS_PIN, machine.Pin.OUT) try: sd = sdcard.SDCard(spi, cs) os.mount(sd, "/sd") print("SD CARD INITIALIZED.") except Exception as e: print("SD CARD FAILED, OR NOT PRESENT!", e) raise SystemExit file_path = "/sd/esp32.txt" # Open file for writing (append mode) try: f = open(file_path, "a") f.write("Created by newbiely.com\n") # write a line to esp32.txt f.write("Learn ESP32 and SD Card\n") # write another line to esp32.txt f.close() except Exception as e: print("SD Card: Issue encountered while attempting to open the file esp32.txt", e) # Open file for reading line-by-line try: f = open(file_path, "r") line_count = 0 while True: line = f.readline() # read line-by-line from Micro SD Card if not line: break line_count += 1 print("Line {}: {}".format(line_count, line.strip())) # print the line to the Shell f.close() except Exception as e: print("SD Card: Issue encountered while attempting to open the file esp32.txt", e) os.umount("/sd")
  • The result on the Shell
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot SD CARD INITIALIZED. Line 1: Created by newbiely.com Line 2: Learn ESP32 and SD Card
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡

※ NOTE THAT:

Additional lines may appear in the Shell if the file already contains data from earlier runs.

ESP32 MicroPython - Overwriting a File on Micro SD Card

Since data is appended by default, the easiest approach to overwrite a file is to remove the existing file first and then create a fresh one with the same name.

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-micro-sd-card """ import machine import os import sdcard # Define SPI pins for the Micro SD Card module SPI_SCK_PIN = 18 # The ESP32 pin GPIO18 connected to SCK SPI_MOSI_PIN = 23 # The ESP32 pin GPIO23 connected to MOSI SPI_MISO_PIN = 19 # The ESP32 pin GPIO19 connected to MISO SPI_CS_PIN = 5 # The ESP32 pin GPIO5 connected to SS (CS) # Initialize SD card using SoftSPI and sdcard driver spi = machine.SoftSPI(baudrate=1000000, polarity=0, phase=0, sck=machine.Pin(SPI_SCK_PIN), mosi=machine.Pin(SPI_MOSI_PIN), miso=machine.Pin(SPI_MISO_PIN)) cs = machine.Pin(SPI_CS_PIN, machine.Pin.OUT) try: sd = sdcard.SDCard(spi, cs) os.mount(sd, "/sd") print("SD CARD INITIALIZED.") except Exception as e: print("SD CARD FAILED, OR NOT PRESENT!", e) raise SystemExit file_path = "/sd/esp32.txt" # Delete the file if it exists (to overwrite) try: os.remove(file_path) except OSError: pass # Create new file by opening file for writing try: f = open(file_path, "w") f.write("Created by newbiely.com\n") # write a line to esp32.txt f.write("Learn ESP32 and SD Card\n") # write another line to esp32.txt f.close() except Exception as e: print("SD Card: Issue encountered while attempting to open the file esp32.txt", e) # Open file for reading try: f = open(file_path, "r") while True: ch = f.read(1) # read characters one by one from Micro SD Card if not ch: break print(ch, end="") # print the character to the Shell f.close() except Exception as e: print("SD Card: Issue encountered while attempting to open the file esp32.txt", e) os.umount("/sd")
  • The result on the Shell
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot SD CARD INITIALIZED. Created by newbiely.com Learn ESP32 and SD Card
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡
  • Restart the ESP32
  • Verify whether the file content in the Shell was replaced or appended.

Alternatively, you can remove the Micro SD Card from the module and inspect the file on your PC (a USB SD Card reader is required)

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!