#include <ArduinoJson.h>
#include <SPI.h>
#include <SD.h>
const int potPin = 34;
const int ledPin = 25;
const int buzzerPin = 26;
const int chipSelect = 5;
unsigned long tempOver35StartTime = 0;
bool isTempOver35 = false;
bool alertActive = false;
File dataFile;
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(chipSelect, OUTPUT);
if (!SD.begin(chipSelect)) {
Serial.println("Initialization of SD card failed!");
return;
}
Serial.println("Initialization of SD card successful!");
}
void loop() {
float temperature = readTemperature();
Serial.print("Simulated Temperature: ");
Serial.println(temperature);
if (temperature > 35) {
if (!isTempOver35) {
tempOver35StartTime = millis();
isTempOver35 = true;
} else if (millis() - tempOver35StartTime > 10000 && !alertActive) {
activateAlert();
alertActive = true;
logData(temperature, true);
}
} else {
isTempOver35 = false;
if (alertActive) {
delay(5000);
deactivateAlert();
alertActive = false;
logData(temperature, false);
}
}
delay(1000);
}
float readTemperature() {
int sensorValue = analogRead(potPin);
float voltage = sensorValue * (3.3 / 4095.0);
float temperature = voltage * 100.0;
return temperature;
}
void activateAlert() {
digitalWrite(ledPin, HIGH);
digitalWrite(buzzerPin, HIGH);
Serial.println("Alert activated: Temperature over 35°C");
}
void deactivateAlert() {
digitalWrite(ledPin, LOW);
digitalWrite(buzzerPin, LOW);
Serial.println("Alert deactivated: Temperature below 35°C");
}
void logData(float temperature, bool alert) {
if (SD.exists("temperature_log.json")) {
dataFile = SD.open("temperature_log.json", FILE_WRITE);
} else {
dataFile = SD.open("temperature_log.json", FILE_WRITE);
dataFile.println("[");
}
if (dataFile) {
DynamicJsonDocument doc(256);
doc["timestamp"] = millis();
doc["temperature"] = temperature;
doc["alert"] = alert;
if (SD.exists("temperature_log.json")) {
dataFile.seek(dataFile.size() - 1);
dataFile.println(",");
}
serializeJson(doc, dataFile);
dataFile.println("]");
dataFile.close();
} else {
Serial.println("Error opening file for writing");
}
}