🛠 Enregistrer des données sur carte SD via le bus SPI
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
- 1 × Arduino Mega 2560 + USB cable
- 1 × 5 V tolerant micro SD adapter module or 3.3 V adapter + level shifter
- 1 × micro SD card formatted as FAT16/FAT32
- 1 × potentiometer on A0 (test data source)
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
- Forgetting
pinMode(SS, OUTPUT): without this, if pin 53 floats as an input, the Mega switches to SPI slave mode and the bus stops working. - Card formatted as exFAT or NTFS: the SD library only accepts FAT16/FAT32 (cards up to 32 GB come factory-formatted as FAT32).
- Forgetting
closeafter writing: data remains in the buffer and the file appears empty. - 5 V levels on the MOSI/SCK/CS lines of a 3.3 V card without adaptation: this will eventually destroy the module.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinodouble-servo.inoArduinopont-uart.inoArduinopwm-respiration.inoArduinopotentiometre-plotter.inoArduino