Subscribe to Arduino Academy and start learning today for FREE!

SD Card Datalogging with the DHT22 Temp Humidity Sensor

We were asked to do a tutorial explaining how to do logging with the DHT22 Temperature Humidity Sensor. This is a little tricky, as the sensor outputs floats, and we send strings to the SD card, I’ve put together a float to string feature to help with this. Please see our previous tutorials on how to connect the DHT22, and how to connect a SD card module. If you are able to get that to run, then you are ready for this tutorial.

Here is the sketch for the logging feature. It reads the DHT22, converts the floats to strings, and writes the comma delimited data to the SD card. Video is below!

Become the Maker you were born to be. Try Arduino Academy for FREE!



#include “DHT.h”

#define DHTPIN 7     // what pin we’re connected to
#define DHTTYPE DHT22   // DHT 22 (AM2302)

#include <SPI.h>
#include <SD.h>

const int chipSelect = 10;

void setup()
// Open serial communications and wait for port to open:
while (!Serial) {
// wait for serial port to connect. Needed for Leonardo only

Serial.print(“Initializing SD card…”);
// make sure that the default chip select pin is set to
// output, even if you don’t use it:
pinMode(10, OUTPUT);

// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println(“Card failed, or not present”);
// don’t do anything more:
Serial.println(“card initialized.”);

Serial.println(“DHTxx test!”);


void loop()

// Wait a few seconds between measurements.

// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds ‘old’ (its a very slow sensor)
float h = dht.readHumidity();
// 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(h) || isnan(t) || isnan(f)) {
Serial.println(“Failed to read from DHT sensor!”);

// Compute heat index
// Must send in temp in Fahrenheit!
float hi = dht.computeHeatIndex(f, h);

Serial.print(“Humidity: “);
Serial.print(” %t”);
Serial.print(“Temperature: “);
Serial.println(” *Ft”);

// make a string for assembling the data to log:
String dataString = “”;

char buffer[10];
String stringH = dtostrf(h,6,2,buffer);
dataString = stringH;
dataString += “,”;
String stringF = dtostrf(f,6,2,buffer);
dataString += stringF;

// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile =“datalog.txt”, FILE_WRITE);

// if the file is available, write to it:
if (dataFile) {
// print to the serial port too:
// if the file isn’t open, pop up an error:
else {
Serial.println(“error opening datalog.txt”);

Become the Maker you were born to be. Try Arduino Academy for FREE!



Notify of
Inline Feedbacks
View all comments


Would love your thoughts, please comment.x