Data logging

Theory

A data logger enables long running experiments. Your Arduino can periodically read from the sensors and save the results to an SD card. When you are done, you can connect the SD card to a computer and open the file as a spreadsheet for analysis.

Code

#include <SdFat.h>
#include <RTClib.h>
#include <Wire.h>

DS1307 rtc;
SdFat sd;
SdFile file;

void setup() {
  // Set the serial baud rate  
  Serial.begin(9600);

  // Initialise the real time clock
  Wire.begin();
  rtc.begin();

  // Try to communicate with an SD card
  if (sd.begin()) {
    Serial.println("Initialised SD card.");
  } else {
   Serial.println("Failed to initialise SD card.");
  }
}

void loop() {
  
  if (file.open("data.csv", O_CREAT | O_WRITE | O_APPEND)) {
    // Obtain the current time and format it nicely
    char timestring [] = "DD/MM/YYYY hh:mm:ss"; // specify the date format 
    DateTime now = rtc.now();
    now.format(timestring);

    // Write to the file and also the serial port
    file.print(timestring);
    Serial.print(timestring);

    // Insert a comma separation
    file.print(",");
    Serial.print(",");

    // Store a number 
    int value1 = 7; // TODO read this from a sensor!
    file.print(value1);
    Serial.print(value1);

    // Insert a comma separation
    file.print(",");
    Serial.print(",");
    
    // Store another number 
    float value2 = 88.4; // TODO read this from a sensor!
    file.print(value2);
    Serial.print(value2);
    
    // finish
    file.println();
    file.close();
    Serial.println();
  } else {
    Serial.println("Failed to open the file.");
  }

  // How long until the next measurement?
  delay(1000);
}

Run the above code. It will create a file “data.csv” on the SD card and begin writing time-stamped values into this file.

Use the Serial Monitor to inspect the values being written.

Using an SD card reader, open the file in Excel.

Exercise

Build a data logger using one or more of the sensors that we have examined so far in this workshop. You will need to combine your previous code with the above.

If your data logger is failing to open the file, you might need to restart the Arduino by pressing the reset button next to the SD card.

Topics for workshop discussion

Extension task

Use a LED as a status indicator to indicate whether the device is currently working correctly. Light up a red LED to indicate when an error occurs, such as the file cannot be written to. You could imagine adding a green LED to signal success. If you could look over at the logger and see a periodic green flash, you would be comfortable that it was still running correctly.


This work is licensed under a Creative Commons Attribution 4.0 International License. For comments or corrections, please contact [email protected].