#include <SD.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <WiFi.h>
#define SWITCH1 12
#define SWITCH2 14
#define RED_LED 15
#define GREEN_LED 2
unsigned long switch1_time = 0;
unsigned long switch2_time = 0;
bool switch1_state = 0;
bool switch2_state = 0;
void setup() {
pinMode(SWITCH1, INPUT);
pinMode(SWITCH2, INPUT);
pinMode(RED_LED, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
// Initialize SD card and create a file
if (!SD.begin()) {
Serial.println("Error initializing SD card");
return;
}
File logFile = SD.open("log.txt", FILE_WRITE);
if (!logFile) {
Serial.println("Error creating log file");
return;
}
Serial.begin(115200); //initialize serial communication
}
void loop() {
// Check if switch 1 is pulled high
if (digitalRead(SWITCH1) == HIGH) {
switch1_time = millis();
switch1_state = 1;
}
// Check if switch 2 is pulled high
if (digitalRead(SWITCH2) == HIGH) {
switch2_time = millis();
switch2_state = 1;
}
// Check if both switches have been pulled high for more than 500ms
if (switch1_state && switch2_state && (millis() - switch1_time > 500) && (millis() - switch2_time > 500)) {
// Turn on red LED
digitalWrite(RED_LED, HIGH);
// Get current time and date
struct tm timeinfo;
if(!getLocalTime(&timeinfo)){
Serial.println("Failed to obtain time");
return;
}
char timeStringBuff[20];
strftime(timeStringBuff, sizeof(timeStringBuff), "%Y-%m-%d %H:%M:%S", &timeinfo);
String timeString = String(timeStringBuff);
// Write log entry to file
File logFile = SD.open("log.txt", FILE_WRITE);
if (logFile) {
String log = "Event logged at: " + timeString;
logFile.println(log);
logFile.close();
}
else {
Serial.println("Error opening log file");
}
Serial.print("Event logged at: ");
Serial.println(timeString); //Print the log entry to the serial monitor
}
// Check if both switches are no longer pulled high
if (digitalRead(SWITCH1) == LOW && digitalRead(SWITCH2) == LOW) {
// Turn off red LED and turn on green LED
digitalWrite(RED_LED, LOW);
digitalWrite(GREEN_LED, HIGH);
// Reset switch state
switch1_state = 0;
switch2_state = 0;
}
}