Snippets

Alexander Boden Arduino Weatherstation

Created by Alexander Boden
/*
  SD card datalogger with DHT-22 sensor and Ethernet Shield (with sd card reader/writer)
 */

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

#define DHTPIN 2 // Pin of the DHT sensor
#define DHTTYPE DHT22 // Change e.g. to DHT11 if using different sensor

// Connect pin 1 (left) to +5V, pin 2 to DHTPIN (here: 2), and pin 4 to GROUND. 
// Add a 10K resistor between +5V/pin1 and pin 2.

DHT dht(DHTPIN, DHTTYPE);

// On the Ethernet Shield, CS is pin 4. Note that even if it's not
// used as the CS pin, the hardware CS pin (10 on most Arduino boards,
// 53 on the Mega) must be left as an output or the SD library
// functions will not work.
const int chipSelect = 4;

// Here we define some values for the program. 
long timestamp = 0;
long interval = 60000 * 5; // Last value defines minute interval;
String dataString = "";

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  
  randomSeed(analogRead(0));

  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.");
  
  dht.begin();
  Serial.println("DHT sensor initialized.");
  
}

void loop()
{   
    //(Re-)set the data
    dataString = "";
    String temp = "";
    String humid = "";
    timestamp = millis();
    
    // Reading the values from the sensor ...
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    
    // Check if the sensor has given us data.
    if (isnan(h) || isnan(t)) {
      temp = "--";
      humid = "--";
      Serial.write("Failed to read from DHT sensor!");
    } else {
      // Convert floats to strings ... tricky ...
      char tmp[25];
      temp = dtostrf(t,1,2,tmp);
      humid = dtostrf(h,1,2,tmp);       
    }      
    
    // And write it to the logger ...
    dataString = String(timestamp/60000, DEC) + ", "  + temp + "C, " + humid + "%";
    write();
    
    delay(interval);
    
}
  
void write() {

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

}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.