/*
* SD Card Data Logger over SPI
*
* This Arduino sketch demonstrates interfacing an SD card over SPI for data logging.
* It uses the built-in SD library, which handles the low-level SD protocol (CMD0, ACMD41 init, FAT filesystem, etc.)
* over SPI. This is the most practical and reliable way for most embedded projects.
*
* Hardware Connections (for Arduino Uno/Nano):
* - SD Card Module Pins:
* - VCC -> 3.3V or 5V (check module specs)
* - GND -> GND
* - MISO -> Pin 12 (SPI MISO)
* - MOSI -> Pin 11 (SPI MOSI)
* - SCK -> Pin 13 (SPI SCK)
* - CS -> Pin 10 (configurable)
*
* Features:
* - Initializes SD card.
* - Logs timestamp + analog sensor value (A0) to "datalog.txt" every 2 seconds.
* - Handles errors gracefully.
*
* Tested on Arduino Uno with microSD card formatted as FAT16/32.
* For low-level SPI implementation without SD lib, see comments at end.
*/
#include <SPI.h>
#include <SD.h>
const int chipSelect = 10; // SD Card CS pin
const int sensorPin = A0; // Example sensor input
void setup() {
Serial.begin(9600);
while (!Serial) {} // Wait for Serial Monitor
Serial.print("Initializing SD card...");
if (!SD.begin(chipSelect)) {
Serial.println("initialization failed!");
while (1) {
digitalWrite(LED_BUILTIN, HIGH);
delay(200);
digitalWrite(LED_BUILTIN, LOW);
delay(200);
}
}
Serial.println(" done.");
}
void loop() {
// Read sensor data (example: analog value)
int sensorValue = analogRead(sensorPin);
// Open file in append mode
File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
// Log timestamp (millis()), sensor value, and newline
dataFile.print(millis());
dataFile.print(",");
dataFile.print(sensorValue);
dataFile.println();
dataFile.close();
// Echo to Serial for debugging
Serial.print("Logged: ");
Serial.print(millis());
Serial.print(",");
Serial.println(sensorValue);
} else {
Serial.println("Error opening datalog.txt");
}
delay(2000); // Log every 2 seconds
}
How It Works
- SPI Setup: Arduino's
SD library uses the hardware SPI peripheral internally.
- Initialization:
SD.begin(chipSelect) sends CMD0 (GO_IDLE), CMD8, ACMD41 (until ready), CMD58 (OCR check).
- File Operations: Mounts FAT filesystem, opens file in write/append mode, writes data blocks via CMD24/25.
- Data Logging: Appends CSV-like data. File grows indefinitely (use
SD.remove() or rollover if needed).
- Error Handling: Blinks LED on init failure; checks file open.
Usage Tips
- Format SD Card: Use FAT16/FAT32 (exFAT may not work). Tools: SD Card Formatter.
- Power: Use 3.3V logic level shifter if Arduino is 5V.
- High-Speed Logging: For faster rates, use
FILE_WRITE | O_CREAT and buffer writes.
- Other Platforms:
- ESP32: Same code works (CS=5).
- RPi Pico (CircuitPython): Use
adafruit_sdcard lib.
- STM32: Use FatFs + HAL_SPI.
Low-Level SPI Implementation (Without SD Library)
For a from-scratch driver (e.g., no filesystem, raw block writes), here's a minimal C snippet for AVR/Arduino:
// Low-level SD SPI functions (add to above sketch, replace SD lib)
#define CS_PIN 10
#define SPI_SPEED F_CPU / 4 // Start slow for init
uint8_t sd_cmd(uint8_t cmd, uint32_t arg) {
digitalWrite(CS_PIN, LOW);
SPI.transfer(cmd | 0x40); // CMD prefix
SPI.transfer((uint8_t)(arg >> 24));
SPI.transfer((uint8_t)(arg >> 16));
SPI.transfer((uint8_t)(arg >> 8));
SPI.transfer((uint8_t)arg);
SPI.transfer(0x95); // Dummy CRC for CMD0/CMD8
uint8_t resp = 0xFF;
for (int i = 0; i < 10; i++) resp = SPI.transfer(0xFF); // Wait response
digitalWrite(CS_PIN, HIGH);
return resp;
}
bool sd_init() {
pinMode(CS_PIN, OUTPUT);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV128); // Slow init
// CMD0: Reset
if (sd_cmd(0, 0) != 0x01) return false;
// CMD8: Check voltage
sd_cmd(8, 0x1AA);
// ACMD41: Init (loop until ready)
uint32_t t = millis();
while (millis() - t < 1000) {
if (sd_cmd(1, 0) == 0x00) break; // CMD1 equiv for SPI
if (sd_cmd(55, 0) != 0x01 || sd_cmd(41, 0x40000000) != 0x00) return false;
}
SPI.setClockDivider(SPI_CLOCK_DIV4); // Speed up
return true;
}
bool sd_write_block(uint32_t block, uint8_t* data) {
if (sd_cmd(24, block * 512) != 0x00) return false; // CMD24
digitalWrite(CS_PIN, LOW);
SPI.transfer(0xFF); // Dummy
for (int i = 0; i < 512; i++) SPI.transfer(data[i]);
SPI.transfer(0xFD); // CRC dummy
uint8_t resp = SPI.transfer(0xFF);
digitalWrite(CS_PIN, HIGH);
SPI.transfer(0xFF); // Ensure write finish
return (resp & 0x1F) == 0x05;
}
// Usage: uint8_t buf[512] = {0}; /* fill buf */ sd_write_block(0, buf);
This low-level version skips FAT/filesystem (raw LBA blocks). For full logging, integrate FatFs library.
If you need adaptations (e.g., STM32 HAL, no RTOS, multi-sector writes), specify your MCU/platform! 🔍