Using SD cards

Using SD cards#

SD cards are appealing as they are compact, portable and more memory than you are likely to ever need.

Requirements

  1. A Pico

  2. A SD card shield (we used a Diligent PmodSD module)

  3. A SD card

Code#

Hardware set-up#

Connecting an SD card to the Pico is mostly straightforward but needs some attention to keep track of the connections.

The diagram below is based on the Diligent PmodSD module - find documentation here.

Watch out!

The order of the pins shown below may not be the same for your SD card module! Make sure you check the pinout diagram of your own module which should be available online through the manufacturer.

../../_images/SDCard_wiring.png

This SD card module communicates via the SPI interface, meaning we require 6 connections to the Pico.

The TX (MOSI), RX (MISO) and SCK need to be connected to specific pins on the Pico (check the pinout diagram). On the other hand, the CS (Chip Select) can be connected to any GP pin.

Coding#

To save data to an SD card, you can incorporate the following code with the rest of your program.

import board
import busio
import sdcardio
import storage
import time
import microcontroller
import digitalio

spi = busio.SPI(board.GP2, MOSI = board.GP3, MISO = board.GP4)   #Assign the SPI pins
cs = board.GP0
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

sdcard = sdcardio.SDCard(spi, cs)   #Create an object for the SD card
vfs = storage.VfsFat(sdcard)        #Create an object for the SD card's filesystem
storage.mount(vfs, "/sd")           #Represent the filesystem with an "sd" folder

filepath = "/sd/temperature.txt"    #Create a variable to hold the filepath

with open(filepath, "a") as f:
    f.write('Starting new set of measurements for CPU temperature (Celcius)\n')
    f.write('')
print('Writing to SD card\n')

while True:
    try:
        with open(filepath, "a") as f:
            temp = microcontroller.cpu.temperature
            led.value = True
            f.write(f"CPU temperature: {temp}\n")
            print(f"CPU temperature: {temp}\n")
    except OSError as e:
        led.value = False
        time.sleep(0.5)
        led.value = True
        print(e)
    time.sleep(5)

When you run the code, you should see a folder called sd appear in your CIRCUITPY drive. This folder is a placeholder and won’t actually contain your .txt or .csv file. Instead, if everything is set up correctly, the datafile should be saving to your SD card’s memory - which you will be able to access when you read the SD card separately.

You will notice that with the except statement, we have programmed the onboard LED to blink when there is an error preventing the data from saving correctly.