Sketch: #5
Uno temp/humidty logger
General |
Video List |
Video Latest |
Carousel |
Carousel Recent |
D&D 5e |
Fantasy Grounds |
Insult |
Secrets |
Sketches |
Sensor Readings
I need to work on the formatting of the code block, but the base is there for now.
---- Log it to an SD card
//Libraries
#include <SPI.h>
#include <SD.h>
#include <DHT.h>
//Constants
#define DHTPIN 7 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
//Variables
const int chipSelect = 4;
int chk;
float hum; //Stores humidity value
float temp; //Stores temperature value
float fahrenheit; //Stores fahrenheit temp
String JSONSensor = "";
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
dht.begin();
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
// 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:
while (1);
}
Serial.println("card initialized.");
}
void loop() {
//get sensor data
do_temp();
delay(1000);
// 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(JSONSensor);
dataFile.close();
// print to the serial port too:
Serial.println("Wrote: " + JSONSensor);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}
void do_temp(){
//Read data and store it to variables hum and temp
hum = dht.readHumidity();
temp= dht.readTemperature();
fahrenheit = 1.8 * temp + 32;
// make a string for assembling the data to log:
String dataString = "{ \"humidity\": "+ String(hum) + ", ";
dataString += "\"Celsius\": "+ String(temp) + ", ";
dataString += "\"Fahrenheit\": "+ String(fahrenheit) + "}";
JSONSensor = dataString;
}