Arduino Temperature Data Logger with SD Card Module

This post shows you how to create a temperature Arduino data logger. We’ll use the DHT11 to measure temperature, the real time clock (RTC) module to take time stamps and the SD card module to save the data on the SD card.

Recommended resources:

Parts required

Here’s a complete list of the parts required for this project:

Note: alternatively to the SD card module, you can use a data logging shield. The data logging shield comes with built-in RTC and a prototyping area for soldering connections, sensors, etc..

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Schematics

The following figure shows the circuit’s schematics for this project.

Note: make sure your SD card is formatted and working properly. Read “Guide to SD card module with Arduino“.

Installing the DHT sensor library

For this project you need to install the DHT library to read from the DHT11 sensor.

  1. Click here to download the DHT-sensor-library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get DHT-sensor-library-master folder
  3. Rename your folder from DHT-sensor-library-master to DHT
  4. Move the DHT folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Code

Copy the following code to your Arduino IDE and upload it to your Arduino board.

/*
 * Rui Santos 
 * Complete Project Details https://randomnerdtutorials.com
 */

#include <SPI.h> //for the SD card module
#include <SD.h> // for the SD card
#include <DHT.h> // for the DHT sensor
#include <RTClib.h> // for the RTC

//define DHT pin
#define DHTPIN 2     // what pin we're connected to

// uncomment whatever type you're using
#define DHTTYPE DHT11   // DHT 11 
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);

// change this to match your SD shield or module;
// Arduino Ethernet shield and modules: pin 4
// Data loggin SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = 4; 

// Create a file to store the data
File myFile;

// RTC
RTC_DS1307 rtc;

void setup() {
  //initializing the DHT sensor
  dht.begin();

  //initializing Serial monitor
  Serial.begin(9600);
  
  // setup for the RTC
  while(!Serial); // for Leonardo/Micro/Zero
    if(! rtc.begin()) {
      Serial.println("Couldn't find RTC");
      while (1);
    }
    else {
      // following line sets the RTC to the date & time this sketch was compiled
      rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    }
    if(! rtc.isrunning()) {
      Serial.println("RTC is NOT running!");
    }
    
  // setup for the SD card
  Serial.print("Initializing SD card...");

  if(!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
    
  //open file
  myFile=SD.open("DATA.txt", FILE_WRITE);

  // if the file opened ok, write to it:
  if (myFile) {
    Serial.println("File opened ok");
    // print the headings for our data
    myFile.println("Date,Time,Temperature ºC");
  }
  myFile.close();
}

void loggingTime() {
  DateTime now = rtc.now();
  myFile = SD.open("DATA.txt", FILE_WRITE);
  if (myFile) {
    myFile.print(now.year(), DEC);
    myFile.print('/');
    myFile.print(now.month(), DEC);
    myFile.print('/');
    myFile.print(now.day(), DEC);
    myFile.print(',');
    myFile.print(now.hour(), DEC);
    myFile.print(':');
    myFile.print(now.minute(), DEC);
    myFile.print(':');
    myFile.print(now.second(), DEC);
    myFile.print(",");
  }
  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.println(now.day(), DEC);
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.println(now.second(), DEC);
  myFile.close();
  delay(1000);  
}

void loggingTemperature() {
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  //float f = dht.readTemperature(true);
  
  // Check if any reads failed and exit early (to try again).
  if  (isnan(t) /*|| isnan(f)*/) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  
  //debugging purposes
  Serial.print("Temperature: "); 
  Serial.print(t);
  Serial.println(" *C");
  //Serial.print(f);
  //Serial.println(" *F\t"); 
  
  myFile = SD.open("DATA.txt", FILE_WRITE);
  if (myFile) {
    Serial.println("open with success");
    myFile.print(t);
    myFile.println(",");
  }
  myFile.close();
}

void loop() {
  loggingTime();
  loggingTemperature();
  delay(5000);
}

View raw code

In this code we create a loggingTime() function and a loggingTemperature() function that we call in the loop() to log the time and temperature to the DATA.txt file in the SD card.

Open the Serial Monitor at a baud rate of 9600 and check if everything is working properly.

Getting the data from the SD card

Let this project run for a few hours to gather a decent amount of data, and when you’re happy with the data logging period, shut down the Arduino and remove the SD from the SD card module.

Insert the SD card on your computer, open it, and you should have a DATA.txt file with the collected data.

You can open the data with a text editor, or use a spreadsheet to analyse and process your data.

The data is separated by commas, and each reading is in a new line. In this format, you can easily import data to Excel or other data processing software.

Wrapping up

This is a great project to learn how to use the SD card module with Arduino to build a data logger. You can apply this concept in pretty much any project you’d like.

If you like Arduino projects, make sure you check our latest Arduino course: Arduino Step-by-step Projects – Build 23 Projects

We hope you’ve found this project useful.

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

45 thoughts on “Arduino Temperature Data Logger with SD Card Module”

  1. Rui, I could not get this sketch to work initially. After a lot of ‘head scratching’, I discovered that only the RTClib library from Adafruit would work. Other versions could not find the RTC module.

    Reply
    • Hi.
      Yes, you can add an RTC.
      We don’t have any tutorial with that specific RTC.
      But you can take a look at DS1302 RTC module tutorial on the Arduino official website: playground.arduino.cc/Main/DS1302
      I hope this helps 🙂
      Regards,
      Sara 🙂

      Reply
  2. it was a great post, was just looking for something like this, can we get date & time as strings with a DS1307, thank u

    Reply
  3. Hi and Obrigado for your project!
    Inadvertently I purchased the DHT22 which only has 3 pins whereas the DHT 11 has 4. Is it possible to use the DHT22 and if so could you tell me what connections I should make? This is what I bought:
    amazon.de/DHT11-Digitaler-Temperatursensor-und-Feuchtigkeitssensor/dp/B07MN7TMXH

    Reply
    • Hi Michael.
      Yes, you can use that one.
      Usually those modules have the following pinout from left to right:
      VCC – Data – GND

      You can connect the data pin directly to an Arduino pin. You don’t need the resistor, because these modules already have a resistor built-in.
      Regards,
      Sara

      Reply
  4. Hi Sara,
    Everything is working perfectly (including measuring humidity) although my 3-pin sensor still seems to need the resistor.
    I have now removed the Uno and installed a Nano Every as I would like to design a circuit board (with Fritzing) and make it completely stand-alone.

    But … for my project I need to add another two sensors. I will be measuring temperature inside and outside (2 sensors) and water temperature (3rd sensor, probably DS18b20 Waterproof Temperature Sensor). So I have a couple of questions:

    1 – Can I add two extra sensors, and if so, which pins should I connect them to. Would 3 and 5 be OK? Is it critical?

    2 – What would you suggest is the maximum length cable for the sensors? The board will be in a swimming pool area with the water sensor nearby, so no problem there. But how far away can I put the outside temperature sensor – is 5 metres too far?

    3 – Would it be a good idea to use a 12v power supply (through VIN) rather than 5 volt through the USB port?

    Your project has inspired me and I’m learning a lot from it – thank you so much!

    Michael

    Reply
    • Hi Michael.
      You should have no problem adding more sensors. Those pins seem good to me. But you need to experiment and see how the board behaves.
      As for the maximum length, that is something that you have to try yourself. Very long cables introduce noise in your readings. But you really need to experiment to see the results.
      You can power the Arduino through the VIN pin using 6 to 12V power source. So, you should have no problem.

      I’m glad you’re learning from our tutorials.
      Thank you so much for following our work.
      Regards,
      Sara

      Reply
  5. Hello,
    I followed the tutorial and finf it exactly what I want. I went out and got the RTC you suggested as well but it kept on displaying some other times so I followed your tutorial on https://randomnerdtutorials.com/guide-for-real-time-clock-rtc-module-with-arduino-ds1307-and-ds3231/ (I did the // to Retain the time in the Real Time Clock) which was working until I put the RTC back onto the above project. Its now displaying the incorrect time again. Any clues?

    Reply
    • Hi Paul.
      To retain the time on the RTC, it needs to be powered by its battery.
      Are you using a battery on the RTC?
      Regards,
      Sara

      Reply
      • Hi Sara.
        Yes I am using the battery on the RTC. I checked the battery and 3.7V so is good there.
        Do I need to alter any code in the Arduino Temp Logger sketch to prevent it from resetting the time when this sketch first boots up? These times seem all over the place. The RTC is brand new from an dedicated electronics store in Australia (Jcar)

        I’ve ran the RTC clock again and put it straight back into the powered down nano (but haven’t reloaded the sketch again) to see if this keeps the time up to date.

        The Nano pins are exactly the same which I’m really happy about – thanks for the additional instructions for those who don’t have a Uno’s. I really like these tutorials on this site as it gives additional info for those who have found other boards to explore on.

        Although I have had the RTC problem I love this project so much I have already made up a protoboard and am using the project already to monitor temps (soldered female headers in case I want to recycle any parts in the future) Although its pretty ugly to look at I am so happy.

        Reply
        • Hi Paul.
          That’s great what you’re doing with this project.
          You don’t need to change anything on the code.
          When you upload the code, the RTC adjust the date and time for the time you uploaded the sketch.
          I’m not sure what is happening because we created this tutorial a long time ago. But probably, it resets the time every time on boot or reset.
          I think you need to upload the code as it is the first time to adjust the RTC time.
          Then, upload the code again byt with this line commented like so:
          //rtc.adjust(DateTime(F(DATE), F(TIME)));
          I hope this helps.
          Regards,
          Sara

          Reply
          • //rtc.adjust(DateTime(F(DATE), F(TIME)));

            It worked. Hope this helps anyone else who liked the project and has had trouble with the RTC.

            I waited a few days to see if it would be consistent.

            Thank you.

  6. Hello,

    For my first Arduino project, I want to collect 1 year room temperature data. I was curious if this setup is build for this purpose (are the used components able to work for this long?), and what the amount of space one data point takes on the SD card.

    Thanks in advance!

    Reply
  7. Hello,

    Did this with a DS3231 RTC. Was ok but the library doesn’t do isrunning() for the DS_3231.
    Commented that out and reran, and all ran good.

    Reply
  8. Hello,
    I am Ankit Marda, and I am getting the following issue:
    Arduino: 1.8.15 (Windows Store 1.8.49.0) (Windows 10), Board: “Arduino Uno”

    In file included from C:\Users\Ankit\Documents\Arduino\libraries\DHT\DHT_U.cpp:15:0:

    C:\Users\Ankit\Documents\Arduino\libraries\DHT\DHT_U.h:36:10: fatal error: Adafruit_Sensor.h: No such file or directory

    #include <Adafruit_Sensor.h>

    ^~~~~~~~~~~~~~~~~~~

    compilation terminated.

    exit status 1

    Error compiling for board Arduino Uno.

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    Reply
  9. Great post and very well explained. Tried the project and worked like a charm. I believe that the DHT11 can also measure humidity. It will be great to use both features of the sensor. What code line do I need to apply to read and log the humidity? where in the code I should place the additional line?
    I am new in the coding but your feedback will greatly help to understand.
    Thanks again

    Reply
    • Hi.
      To learn how to get humidity from the DHT11 sensor, you can check this tutorial:
      https://randomnerdtutorials.com/complete-guide-for-dht11dht22-humidity-and-temperature-sensor-with-arduino/

      You can change the loggingTemperature() function to also display the humidity.
      See below:

      void loggingTemperature() {
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      // Read temperature as Celsius
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit
      //float f = dht.readTemperature(true);
      float h = dht.readHumidity(); //--> gets humidity

      // Check if any reads failed and exit early (to try again).
      if (isnan(t) /|| isnan(f)/) {
      Serial.println("Failed to read from DHT sensor!");
      return;
      }

      //debugging purposes
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.println(" *C");
      //Serial.print(f);
      //Serial.println(" *F\t");

      myFile = SD.open("DATA.txt", FILE_WRITE);
      if (myFile) {
      Serial.println("open with success");
      myFile.print(t);
      myFile.println(",");
      myFile.print(h); //--> saves humidity
      myFile.print(",");
      }
      myFile.close();
      }

      I hope this helps,
      Regards,
      Sara

      Reply
  10. I’ve a question, I should activate a relay every 20 minutes for 2 minutes, using real time, using rtc ds3231, would you be able to help?

    Reply
  11. almost 6 yrs later and this code and setup still work. thats amazing to me these days lol
    Thank you for this tutorial. good job.

    Reply
  12. Hello Sarah,

    I am working on this sample project, thank you. I want to powered my arduino promini 5v with external 18650 battery so I need to build battery saver code.
    Is it possible to use deep sleep mode? For example
    1. Arduino wakes up.
    2. Collecting data from DHT 11 and RTC Modüle.
    3. Writes up the data on sd card.
    4. Arduino goes to deep sleep for 2 hours.

    What do you think?

    Reply
    • Yes. It should be possible.
      Unfortunately, we don’t have any tutorials for deep sleep or sleep/powerdown mode with the Arduino.
      Regards,
      Sara

      Reply
  13. Thanks for sharing your knowledge. I have a question. How many bytes are needed to store each data series? (Date, Time, Temperature ºC, and humidity).

    Reply
  14. Hi.

    Can this be done without the RTC. By just taking out all the RTC code and setting the temp reading for every 500ms?

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.