Snippets
Created by
Alexander Boden
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | /*
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)
You can clone a snippet to your computer for local editing. Learn more.