Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: Temperature Data Logger

Build an Arduino data logger: read a sensor on a schedule, timestamp readings with a DS3231 clock, write CSV lines to an SD card, and summarize min, max and average.

A data logger records measurements over time so you can look at them later: the temperature of a greenhouse over a week, the battery voltage during a drive, the number of times a door opens. It combines most of what you have learned: a sensor, timing, a clock chip on the I2C bus, a card on the SPI bus, formatted text and a memory-conscious design.

This site cannot run the Arduino IDE, SD cards or sensors. The sketch is real and read-only. The C programs are labelled stand-ins: a CSV writer with fixed readings, and a summary of a logged series, so you can run the logic yourself.

What you need

  • Arduino Uno or Nano
  • DS3231 real-time clock module (I2C, address 0x68, with a coin cell)
  • microSD card module (SPI, chip select on pin 10) with a card formatted FAT32
  • a temperature sensor: a TMP36 on A0 (see temperature sensors)

Wiring: the RTC on SDA and SCL (A4 and A5 on an Uno), the SD module on 11 (MOSI), 12 (MISO), 13 (SCK) and 10 (CS), the TMP36 between 5 V and ground with its signal on A0. SD card modules typically need 5 V and level-shift to 3.3 V on the card side; use a module that includes the shifter. The buses are explained in the I2C lesson and the SPI lesson.

Install the libraries RTClib (by Adafruit) and use the built-in SD library (see installing libraries).

Design

  • A reading every 10 seconds, scheduled with millis().
  • Each line: date,time,celsius (CSV: opens directly in a spreadsheet).
  • A header line is written when the file is created.
  • Data is flushed to the card after each line so a power loss costs at most one reading.
  • Errors (no card, no RTC) are reported once at startup and shown on a status LED.
flowchart LR
  A["Timer (10 s)"] --> B["Read sensor"]
  B --> C["Get time from RTC"]
  C --> D["Format CSV line"]
  D --> E["Append to LOG.CSV"]
  E --> A

One reading cycle.

The sketch

C++
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include "RTClib.h"

const int CS_PIN = 10;
const int SENSOR_PIN = A0;
const int STATUS_LED = 8;
const unsigned long INTERVAL_MS = 10000;

RTC_DS3231 rtc;
unsigned long lastSample = 0;

float readCelsius() {
  long total = 0;
  for (int i = 0; i < 8; i++) {          // average 8 readings to reduce noise
    total += analogRead(SENSOR_PIN);
  }
  float volts = (total / 8.0) * (5.0 / 1023.0);
  return (volts - 0.5) * 100.0;
}

void fail(const __FlashStringHelper *message) {
  Serial.println(message);
  while (true) {                          // blink forever: something is wrong
    digitalWrite(STATUS_LED, !digitalRead(STATUS_LED));
    delay(200);
  }
}

void setup() {
  Serial.begin(9600);
  pinMode(STATUS_LED, OUTPUT);

  if (!rtc.begin()) {
    fail(F("RTC not found"));
  }
  if (rtc.lostPower()) {
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));   // set to compile time
  }
  if (!SD.begin(CS_PIN)) {
    fail(F("SD card failed"));
  }
  if (!SD.exists("LOG.CSV")) {
    File f = SD.open("LOG.CSV", FILE_WRITE);
    f.println(F("date,time,celsius"));
    f.close();
  }
  Serial.println(F("Logging started"));
}

void loop() {
  unsigned long now = millis();
  if (now - lastSample >= INTERVAL_MS) {
    lastSample = now;

    DateTime t = rtc.now();
    float c = readCelsius();

    char line[40];
    char temp[8];
    dtostrf(c, 1, 1, temp);               // float to text (sprintf lacks %f on AVR)
    snprintf(line, sizeof(line), "%04d-%02d-%02d,%02d:%02d:%02d,%s",
             t.year(), t.month(), t.day(), t.hour(), t.minute(), t.second(), temp);

    File f = SD.open("LOG.CSV", FILE_WRITE);
    if (f) {
      f.println(line);
      f.close();                          // close = data safely on the card
      Serial.println(line);
    } else {
      Serial.println(F("write failed"));
    }
  }
}

Notes on the design choices:

  • dtostrf() formats a float into a char buffer; snprintf on AVR boards leaves %f unsupported by default, so the number is converted first.
  • snprintf with a size limit prevents buffer overflow (see the memory lesson).
  • Closing the file after each write is slower but safe. Opening and closing every 10 seconds costs nothing.
  • SD cards have a limit on how often they should be written to; 10 seconds is fine, but writing every few milliseconds is a job for buffering.
  • The DS3231 keeps time with a coin cell and is accurate to about a minute a year. The lostPower() check sets the clock to the compile time, which is slightly wrong; set it properly once and remove that line.

Stand-in: formatting log lines

The C program writes the same CSV lines for a few fixed readings. Compare it with the snprintf in the sketch: the format string is identical apart from the float handling.

C Stand-in: CSV log lines (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: summarizing the log

Once you have data, the first questions are: what was the minimum, the maximum and the average? The Arduino can compute these itself (keeping a running min, max and sum needs only a few variables) and show them on a display, while the full CSV goes to a computer for plotting.

C Stand-in: running min, max and average (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Buffering for faster logging

A 10 second interval is easy. If you need hundreds of samples per second (vibration, audio), write to RAM first. Keep a small buffer (say 64 bytes) and flush it to the card when it fills; each SD write has a large fixed overhead, so one write of 512 bytes is far faster than 50 small ones. The SD library also needs about 500 bytes of RAM for its own buffer, which is another reason to watch memory on an Uno.

Extensions

  • Add humidity with a DHT22 and a second column.
  • Show the latest value on a display.
  • Sleep between samples with the watchdog, and power the SD card only when writing, to run for weeks on batteries.
  • Log events (door opened) with a timestamp using an interrupt instead of a fixed interval.
  • Create a new file per day: 20260314.CSV (8.3 filenames on classic SD).
  • Send the data over the serial port to a PC program or a phone app instead of an SD card.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why close the file after each write?

    Data may sit in a buffer until the file is flushed or closed. Closing guarantees it reaches the card.
  2. 2. What is the role of the DS3231?

    The real-time clock has its own battery and gives timestamps.
  3. 3. Why average eight analog readings in readCelsius()?

    Averaging reduces random noise at the cost of a little time.
  4. 4. Why is dtostrf() used before snprintf?

    On AVR the %f conversion is disabled for size reasons; dtostrf converts the float to text.

Summary

  • A logger repeats: read sensor, fetch time from the RTC, format a CSV line, append to a file, wait.
  • Schedule with millis(), close files after writing, and handle missing hardware with clear error signals.
  • Bounded snprintf and dtostrf format values safely on a small board.
  • Keep running statistics in a few variables, and buffer writes when sampling fast.

Next: Project: Thermostat Fan Controller