#include <LiquidCrystal.h>
#include <SPI.h>
#include "SdFat.h"
#include <EEPROM.h> // Include EEPROM library
const int rs = 13; // RS pin of LCD to Arduino digital pin 13
const int en = 12; // EN pin of LCD to Arduino digital pin 12
const int d4 = 11; // D4 pin of LCD to Arduino digital pin 11
const int d5 = 10; // D5 pin of LCD to Arduino digital pin 10
const int d6 = 9; // D6 pin of LCD to Arduino digital pin 9
const int d7 = 8; // D7 pin of LCD to Arduino digital pin 8
const int buttonPin = 2; // the number of the pushbutton pin
const int ledHigh = 3; // the number of the high LED pin
const int ledLow = 4; // the number of the low LED pin
const int pwmPin = 5; // PWM pin for heater control
const int chipSelect = 6; // CS pin of the SD card module
const int dataInPin = 7; // DI pin of the SD card module
const int clockPin = 1; // SCK pin of the SD card module
const float BETA = 3950; // Beta Coefficient of the thermistor
const float desiredTemp = 40.0; // Desired temperature
const float tolerance = 5.0; // Tolerance for temperature range
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
SdFat SD;
SdFile file;
int buttonState = 0;
void setup() {
lcd.begin(16, 2); // Initialize the LCD with 16 columns and 2 rows
Serial.begin(115200);
pinMode(buttonPin, INPUT);
pinMode(ledHigh, OUTPUT);
pinMode(ledLow, OUTPUT);
pinMode(pwmPin, OUTPUT); // Set PWM pin as output
if (!SD.begin(chipSelect, SPI_HALF_SPEED)) {
Serial.println("SD initialization failed!");
return;
}
}
void loop() {
// Read button state
buttonState = digitalRead(buttonPin);
// Measure temperature
int analogValue = analogRead(A0);
float celsius = 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
// Display live temperature on LCD
lcd.setCursor(0, 0);
lcd.print("Temperature: ");
lcd.print(celsius, 2);
delay(100); // Add a small delay
lcd.print(" C");
// Print temperature to Serial Monitor only when button is pressed
if (buttonState == HIGH) {
// Save current temperature to EEPROM
int address = 0; // EEPROM address to store temperature
float savedTemp = celsius;
EEPROM.put(address, savedTemp);
Serial.println("Temperature saved to EEPROM.");
Serial.print("Current Temp: ");
Serial.print(celsius, 2);
Serial.println(" C");
}
// Control LEDs and heater based on temperature
if (celsius > (desiredTemp + tolerance)) {
digitalWrite(ledHigh, HIGH);
digitalWrite(ledLow, LOW);
analogWrite(pwmPin, 0); // Turn off PWM (heater)
} else if (celsius < (desiredTemp - tolerance)) {
digitalWrite(ledHigh, LOW);
digitalWrite(ledLow, HIGH);
// Calculate PWM duty cycle to heat up
int dutyCycle = map(celsius, desiredTemp - tolerance, desiredTemp, 255, 0); // Inverted for proportional control
dutyCycle = constrain(dutyCycle, 0, 255); // Ensure duty cycle is within valid range
analogWrite(pwmPin, dutyCycle); // Adjust PWM duty cycle
} else {
digitalWrite(ledHigh, LOW);
digitalWrite(ledLow, LOW);
analogWrite(pwmPin, 0); // Turn off PWM (heater)
}
delay(1000); // Delay for readability
}