how to do logging with the DHT22 Temperature Humidity Sensor

Зарегистрирован: 10.04.2015

 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. 

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!


#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(" *F\t");

  // 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");

Video to show effect:

JollyBiber аватар
Зарегистрирован: 08.05.2012

Perfect! Now you can read second page from "Arduino for dummies".

Gippopotam аватар
Зарегистрирован: 12.09.2014

JollyBiber пишет:

Perfect! Now you can read second page from "Arduino for dummies".

...and in some time learn how to blink the LED