Data logger on a microSD card
Log timestamped sensor readings to a CSV file on a microSD card, and read settings from a file on the card.
Communication · Intermediate
In a real product: Flight data recorder (Aerospace and drones): Logs readings to removable storage.
A logger that runs for weeks needs more memory than the board has. A microSD card holds gigabytes, and as a FAT file system a computer can open what the board wrote.
What you'll learn
- Starting the SD library and opening files for reading and appending
- Writing CSV that a spreadsheet opens directly
- Why closing (or flushing) a file matters
How it works
SD.begin(4) initialises the card over SPI (CS on pin 4) and mounts its FAT file system. The sketch first reads CONFIG.TXT, which holds the logging interval in milliseconds: this project's files are copied onto the card when the simulation starts, so edit that file to change it.
Each reading is appended to LOG.CSV as millis,value. Data sits in a 512-byte buffer until the file is closed, so the sketch opens, writes and closes every time: a power cut then loses at most one line.
Try this
- Run it, select the card and watch
LOG.CSVgrow under it. Turn the knob between readings. - Change the number in
CONFIG.TXT(add the file with + in the file list if it is missing) and run again. - Start a new file name for each run (LOG1.CSV, LOG2.CSV...) using
SD.exists().
sketch.ino
// A data logger: microSD card on SPI (CS 4), a knob on A0. Appends "millis,value" to LOG.CSV.
#include <SPI.h>
#include <SD.h>
unsigned long interval = 1000;
void setup() {
Serial.begin(9600);
if (!SD.begin(4)) {
Serial.println("No card");
while (true) {}
}
File config = SD.open("CONFIG.TXT");
if (config) {
interval = config.parseInt();
config.close();
}
if (interval < 100) interval = 1000;
Serial.print("Logging every ");
Serial.print(interval);
Serial.println(" ms");
File log = SD.open("LOG.CSV", FILE_WRITE);
log.println("millis,value");
log.close();
}
void loop() {
int value = analogRead(A0);
File log = SD.open("LOG.CSV", FILE_WRITE);
if (log) {
log.print(millis());
log.print(',');
log.println(value);
log.close();
Serial.print("Logged ");
Serial.println(value);
} else {
Serial.println("Could not open LOG.CSV");
}
delay(interval);
}