#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <RTClib.h>
#include "DHT.h"

// Define pins
#define DHTPIN 2     // DHT22 data pin connected to digital pin 2
#define DHTTYPE DHT22   // DHT 22 (AM2302)
#define CS_PIN 10    // Chip select pin for the SD card

// Initialize objects
DHT dht(DHTPIN, DHTTYPE);
RTC_DS3231 rtc;
File logFile;

void setup() {
  // Start serial communication for debugging
  Serial.begin(9600);
  
  // Initialize DHT sensor
  dht.begin();
  
  // Initialize RTC
  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  
  if (rtc.lostPower()) {
    Serial.println("RTC lost power, setting the time!");
    // Set the time to a known date and time (e.g., compile time)
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  
  // Initialize SD card
  if (!SD.begin(CS_PIN)) {
    Serial.println("Initialization of SD card failed!");
    while (1);
  }
  
  // Open or create log file
  logFile = SD.open("datalog.txt", FILE_WRITE);
  if (!logFile) {
    Serial.println("Failed to open datalog.txt");
    while (1);
  }
}

void loop() {
  // Read temperature and humidity from DHT22
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  
  // Get current timestamp from RTC
  DateTime now = rtc.now();
  
  // Log data
  logFile.print(now.timestamp());
  logFile.print(", ");
  logFile.print(temperature);
  logFile.print(" *C, ");
  logFile.print(humidity);
  logFile.println(" %");
  logFile.flush();  // Ensure data is written to the SD card
  
  // Print to serial monitor for debugging
  Serial.print(now.timestamp());
  Serial.print(", ");
  Serial.print(temperature);
  Serial.print(" *C, ");
  Serial.print(humidity);
  Serial.println(" %");
  
  // Enter sleep mode to save power (you can implement actual sleep mode here)
  delay(60000);  // Log data every minute
}
GND5VSDASCLSQWRTCDS1307+