🛠 Logger sur carte microSD en SPI (mode carte)

RP2040 (generic board / chip) · intermediaire · Schéma : IMG-rp2040-generic-intermediaire-2-rp2040-sdcard-spi.svg — module lecteur microSD relié en SPI à une carte RP2040 générique : GP2 CS, GP3 MOSI, GP4 MISO, GP5 SCK, 3V3 et GND, fichier journal avec horodatages

Objectives

Make your RP2040 board standalone: write files to a microSD card in SPI mode. The RP2040 features 2 SPI controllers (datasheet) and MicroPython includes a generic SD driver (the sdcard module from micropython-lib) that speaks the SD SPI mode (initialization at ~400 kHz followed by faster transfers). Autonomy bonus: the microSD card operates natively at 3.3 V, so no level shifter is needed.

Hardware

Complete code

# logger.py — monte la SD et journalise la température interne
import os, time, machine
from machine import SPI, Pin
import sdcard

spi = SPI(0, baudrate=400_000, polarity=0, phase=0,
          sck=Pin(5), mosi=Pin(3), miso=Pin(4))
cs = Pin(2, Pin.OUT, value=1)

sd = sdcard.SDCard(spi, cs)
fs = os.VfsFat(sd)                 # monte le système de fichiers
os.mount(fs, '/sd')

t0 = time.ticks_ms
adc = machine.ADC(4)               # canal 4 = capteur thermique interne
with open('/sd/log.csv', 'a') as f:
    while True:
        ms = time.ticks_diff(time.ticks_ms, t0)
        mv = adc.read_u16 * 3.3 / 65535
        t = 27.0 - (mv - 0.706) / 0.001721   # formule datasheet RP2040
        f.write('%d,%.2f\n' % (ms, t))
        f.flush                             # écrit réellement la carte
        time.sleep_ms(1000)

Expected verification

After a few seconds, remove the card and read it on a PC: log.csv contains one line per second with the timestamp in ms and the temperature (~27–30 °C at rest; the internal sensor formula, 0.706 V and −1.721 mV/°C, comes from the "Temperature Sensor" section of the RP2040 datasheet). Rerun the script: the file continues to grow (mode "a") — persistence works.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials