#include <LiquidCrystal_I2C.h>
#define I2C_ADDR    0x27
#define LCD_COLUMNS 16
#define LCD_LINES   2
C
unsigned long Ttime;
int keyindex=0;
int in1=0,in2=0,set=20;
const float BETA = 3950;
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);

void setup() 
{
  pinMode(Led,OUTPUT);
  pinMode(R1,OUTPUT);
  pinMode(R2,OUTPUT);
  pinMode(R3,OUTPUT);
  pinMode(R4,OUTPUT);
  pinMode(C1,INPUT_PULLUP);
  pinMode(C2,INPUT_PULLUP);
  pinMode(C3,INPUT_PULLUP);
  digitalWrite(R1,HIGH);
  digitalWrite(R2,HIGH);
  digitalWrite(R3,HIGH);
  digitalWrite(R4,HIGH); 
  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  // Print something
  lcd.setCursor(0, 0);
  lcd.print(F("Hello, world!"));
  lcd.setCursor(0, 1);
  lcd.print(F("enter set temp"));
  delay(2000);
}

void loop() 
{
 int key=scankey();
 if(key!=20)
 {
   Serial.println(key);
   if(keyindex==0)
   {
     lcd.setCursor(0, 1);
     lcd.print(F("Set T:            "));
     lcd.setCursor(6, 1);
     lcd.print(key);
     in1=key;
     keyindex++;
   }else
   {
     lcd.setCursor(7, 1);
     lcd.print(key);
     lcd.print("  ");
     in2=key;
     set=(in1*10)+in2;
     Serial.print("set:");
     Serial.println(set);
     keyindex=0;
   }
   delay(100);
 }
 checkT();
}

void checkT()
{
   if ((millis() - Ttime) > 1000)
  {
  Ttime=millis();
  int analogValue = analogRead(A0);
  float celsius = 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
  Serial.print("Temperature: ");
  Serial.print(celsius);
  Serial.println(" ℃");

   lcd.setCursor(0, 0);
   lcd.print(F("Temperature:"));
   lcd.print(celsius,1);
   lcd.print((char)223);
   lcd.print(F("C  "));

   if(celsius>=set) 
   {
     digitalWrite(Led, HIGH);
     lcd.setCursor(10, 1);
     lcd.print("On    ");
   }
   else
   {
     digitalWrite(Led, LOW);
     lcd.setCursor(10, 1);
     lcd.print("Off    ");
   }
  }
}

int scankey()
{
  int tempKey=20;
  digitalWrite(R1,LOW);
  if(digitalRead(C1)==0){ tempKey=1;}
  else if(digitalRead(C2)==0){ tempKey=2;}
  else if(digitalRead(C3)==0){ tempKey=3;}
  digitalWrite(R1,HIGH);
  
  digitalWrite(R2,LOW);
  if(digitalRead(C1)==0){ tempKey=4;}
  else if(digitalRead(C2)==0){ tempKey=5;}
  else if(digitalRead(C3)==0){ tempKey=6;}
  digitalWrite(R2,HIGH);

  digitalWrite(R3,LOW);
  if(digitalRead(C1)==0){ tempKey=7;}
  else if(digitalRead(C2)==0){ tempKey=8;}
  else if(digitalRead(C3)==0){ tempKey=9;}
  digitalWrite(R3,HIGH);
  
  digitalWrite(R4,LOW);
  if(digitalRead(C1)==0){ tempKey=10;}
  else if(digitalRead(C2)==0){ tempKey=0;}
  else if(digitalRead(C3)==0){ tempKey=12;}
  digitalWrite(R4,HIGH);
  delay(40);
  return tempKey;
}