🛠 Enregistrer des données sur carte SD via le bus SPI

Arduino Mega 2560 (Rev3) · avance · Schéma : IMG-mega-2560-avance-2-spi-sd-card.svg — module carte SD 3,3 V connecté au bus SPI de l’Arduino Mega 2560 (MISO 50, MOSI 51, SCK 52, SS 53) avec adaptation de niveaux 5 V vers 3,3 V

Objectives

Archive measurements to an SD card using the Mega 2560's hardware SPI bus: MISO on pin 50, MOSI on 51, SCK on 52, SS on 53 (also wired to the ICSP connector). You will write a logger that opens a file, records analog inputs with timestamps, and properly handles file opening errors.

Hardware

Electrical caution: An SD card is a 3.3 V component; the Mega's pins are 5 V. A breakout adapter with an integrated regulator often accepts 5 V power, but its logic lines must remain at 3.3 V. Do not power the card via the Mega's 3V3 pin: it is limited to 50 mA, and an SD card during reading can approach or exceed this value.

Complete Code

// Enregistreur SD sur SPI matériel — Mega 2560
#include <SPI.h>
#include <SD.h>

const uint8_t SS_SD = 53;          // SS dédié (SPI : 50/51/52/53)
File journal;
uint32_t t0 = 0;

void setup {
  Serial.begin(115200);
  pinMode(SS_SD, OUTPUT);          // SS en sortie même inutilisé
  if (!SD.begin(SS_SD)) {
    Serial.println(F("SD indisponible : bloqué"));
    while (true) { delay(500); }   // LED 13 clignote via loop ci-dessous
  }
  journal = SD.open("LOG.CSV", FILE_WRITE);
  if (journal) { journal.println("ms;A0"); journal.close; }
  Serial.println(F("SD initialisée"));
}

void loop {
  if (millis - t0 >= 1000) {
    t0 = millis;
    journal = SD.open("LOG.CSV", FILE_WRITE);
    if (journal) {
      journal.print(millis); journal.print(';');
      journal.println(analogRead(A0));
      journal.close;             // close = flush obligatoire
      Serial.println(F("ligne écrite"));
    } else {
      Serial.println(F("échec ouverture LOG.CSV"));
    }
  }
}

Expected Verification

After "SD initialized" appears in the Serial Monitor, a line "line written" scrolls every second. By removing the card and reading LOG.CSV on a PC, you will find the header "ms;A0" followed by measurements at a regular rate.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials