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<stdlib.h>
#include “DHT.h”
#define DHTPIN 7 // what pin we’re connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
#include <SPI.h>
#include <SD.h>
const int chipSelect = 10;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
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:
return;
}
Serial.println(“card initialized.”);
Serial.println(“DHTxx test!”);
dht.begin();
}
void loop()
{
// Wait a few seconds between measurements.
delay(2000);
// 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!”);
return;
}
// Compute heat index
// Must send in temp in Fahrenheit!
float hi = dht.computeHeatIndex(f, h);
Serial.print(“Humidity: “);
Serial.print(h);
Serial.print(” %t”);
Serial.print(“Temperature: “);
Serial.print(f);
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 = SD.open(“datalog.txt”, FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// 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!