#include <DHT.h>
#include <time.h>
#include "SD.h"
#include <SPI.h>
#include <cstdio>
#define DHT_PIN 28
#define DHT_TYPE DHT11
#define SD_PIN 9
float secondsToWait = 1;
char fileName[] = "dht11.csv";
unsigned long long startTimeLoop = 0;
unsigned long long endTimeLoop = 0;
File dataFile;
DHT dht(DHT_PIN, DHT_TYPE);
void setup() {
Serial.begin(115200);
dht.begin();
sleep_ms(5 * 1000);
SD.begin(SD_PIN);
dataFile = SD.open(fileName, FILE_WRITE);
}
void loop() {
sleep_ms((secondsToWait * 1000) - (endTimeLoop - startTimeLoop));
startTimeLoop = time_us_64() / (unsigned long long)1000;
unsigned long long msSinceBoot = startTimeLoop;
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
unsigned long long yearsSinceBoot = msSinceBoot / 1000 / 60 / 60 / 24 / 365;
msSinceBoot -= yearsSinceBoot * 1000 * 60 * 60 * 24 * 365;
unsigned long long daysSinceBoot = msSinceBoot / 1000 / 60 / 60 / 24;
msSinceBoot -= daysSinceBoot * 1000 * 60 * 60 * 24;
unsigned long long hoursSinceBoot = msSinceBoot / 1000 / 60 / 60;
msSinceBoot -= hoursSinceBoot * 1000 * 60 * 60;
unsigned long long minutesSinceBoot = msSinceBoot / 1000 / 60;
msSinceBoot -= minutesSinceBoot * 1000 * 60;
unsigned long long secondsSinceBoot = msSinceBoot / 1000;
msSinceBoot -= secondsSinceBoot * 1000;
char output[100];
sprintf(output, "%lluY:%lluD:%lluh:%llum:%llus:%llums - Temperature = %.2f°C - Humidity = %.2f%%\n", yearsSinceBoot, daysSinceBoot, hoursSinceBoot, minutesSinceBoot, secondsSinceBoot, msSinceBoot, temperature, humidity);
Serial.print(output);
sprintf(output, "%lluY:%lluD:%lluh:%llum:%llus:%llums,%.2f°C,%.2f%%\n", yearsSinceBoot, daysSinceBoot, hoursSinceBoot, minutesSinceBoot, secondsSinceBoot, msSinceBoot, temperature, humidity);
dataFile.print(output);
endTimeLoop = time_us_64() / (unsigned long long)1000;
}