#include <LiquidCrystal_I2C.h>
#define I2C_ADD 0X27
#define COLS 16
#define ROWS 2
#define EN_CLK 2
#define EN_DT 5
#define EN_SW 6
#define TEMP_PIN A0
#define LED 4
int temp;
LiquidCrystal_I2C lcd(I2C_ADD, COLS, ROWS);
// int lastClk = HIGH;
bool tempSet = false;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 5;
bool ledStatus = false; // Track LED state
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
lcd.init();
lcd.backlight();
pinMode(EN_CLK, INPUT);
pinMode(EN_DT, INPUT);
pinMode(EN_SW, INPUT_PULLUP);
pinMode(LED, OUTPUT);
attachInterrupt(digitalPinToInterrupt(EN_CLK), handleEncoder, FALLING);
}
void loop() {
// put your main code here, to run repeatedly:
int actTemp = getReading();
lcd.setCursor(0,0);
lcd.print("TEMP: "+String(actTemp)+" ");
lcd.setCursor(0,1);
lcd.print("SET: "+String(temp));
// lcd.setCursor(8, 1);
// lcd.print("DEACTIVE ");
if(digitalRead(EN_SW) == LOW){
Serial.println("activated");
tempSet = true;
}
if(tempSet){
if(actTemp < temp && !ledStatus){
digitalWrite(LED,HIGH);
ledStatus = true;
Serial.println("activated");
lcd.setCursor(8,1);
lcd.print("ACTIVE ");
}
else if(actTemp >= temp && ledStatus ){
digitalWrite(LED,LOW);
ledStatus = false;
Serial.println("deactivated");
lcd.setCursor(8,1);
lcd.print("DEACTIVE ");
}
delay(200);
}
delay(50);
}
void handleEncoder() {
// int newClk = digitalRead(EN_CLK);
int dtVal = digitalRead(EN_DT);
unsigned long currentTime = millis();
if ((currentTime - lastDebounceTime) > debounceDelay) {
lastDebounceTime = currentTime;
// if (newClk != lastClk){
// lastClk = newClk;
// if(newClk == LOW && dtVal == HIGH){
// temp++;
// Serial.println(temp);
// }
// if(newClk == LOW && dtVal == LOW){
// temp--;
// Serial.println(temp);
// }
// }
if (dtVal == HIGH) {
temp++; // Clockwise
} else {
temp--; // Counter-clockwise
}
Serial.println(temp);
}
}
int getReading(){
const float BETA = 3950; // should match the Beta Coefficient of the thermistor
int analogValue = analogRead(A0);
int celsius = 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
return celsius;
}