0
0
Arduinoprogramming~5 mins

CSV format data logging in Arduino

Choose your learning style9 modes available
Introduction

CSV format helps save data in a simple table form. It is easy to read and use later in programs like Excel.

You want to record sensor readings over time on an SD card.
You need to log temperature and humidity data for analysis.
You want to save button press counts with timestamps.
You want to export Arduino data to a computer for graphing.
Syntax
Arduino
Serial.print(value1);
Serial.print(",");
Serial.println(value2);

Use commas to separate values in one line.

Use println to end the line and start a new row.

Examples
This prints one line with two values separated by a comma: 25,60
Arduino
Serial.print(25);
Serial.print(",");
Serial.println(60);
This prints a header row for CSV columns.
Arduino
Serial.print("Time");
Serial.print(",");
Serial.println("Temp");
This logs the current time and sensor reading as one CSV row.
Arduino
Serial.print(millis());
Serial.print(",");
Serial.println(sensorValue);
Sample Program

This program writes a CSV file on an SD card with time and temperature data. It logs 3 rows with a header.

Arduino
#include <SD.h>
const int chipSelect = 10;

void setup() {
  Serial.begin(9600);
  while (!Serial) {}

  if (!SD.begin(chipSelect)) {
    Serial.println("SD card failed or not present");
    return;
  }

  File dataFile = SD.open("datalog.csv", FILE_WRITE);

  if (dataFile) {
    dataFile.println("Time,Temperature");
    for (int i = 0; i < 3; i++) {
      int temp = 20 + i; // example temperature
      dataFile.print(millis());
      dataFile.print(",");
      dataFile.println(temp);
      delay(1000);
    }
    dataFile.close();
    Serial.println("Data logged to datalog.csv");
  } else {
    Serial.println("Error opening datalog.csv");
  }
}

void loop() {
  // nothing here
}
OutputSuccess
Important Notes

Always include a header row to label your CSV columns.

Use commas to separate each value in a row.

Close the file after writing to save data properly.

Summary

CSV format stores data in rows and columns separated by commas.

Use Serial.print and Serial.println to create CSV lines.

Logging data in CSV makes it easy to analyze later.