#include <LiquidCrystal.h>

#include <PWM.h>

#include <DallasTemperature.h>

#include <OneWire.h>

LiquidCrystal lcd(13, 12, 10, 9, 8, 7);
#define PIN_OUTPUT 3
#define LED 5
volatile int Stop = 2;
int tempsensor = 6;
int Magnet = 11;
int32_t frequency = 10;
int Grades;
double temperature;
double Tmax = 30;
int S;
unsigned long t = 0;
unsigned long tmax = 60000;
int D;
void Drehschalter();
void LCD();
void Abbrechen();
OneWire onewirepin(tempsensor);
DallasTemperature sensors(&onewirepin);

void setup() {

  lcd.begin(16, 2);
  InitTimersSafe();
  bool success = SetPinFrequencySafe(PIN_OUTPUT,frequency);
  sensors.begin();
  pinMode(Magnet, OUTPUT);
  pinMode(Stop, INPUT);
  attachInterrupt(digitalPinToInterrupt(Stop), Abbrechen, CHANGE);
}

void loop() {
 
      while (t < tmax) {
          t = millis();
          digitalWrite(Magnet, HIGH);
          Drehschalter();
          sensors.requestTemperatures();
          temperature=sensors.getTempCByIndex(0);
          D = map(analogRead(1), 0, 1023, 0, 255);
          pwmWrite(PIN_OUTPUT, D);
          analogWrite(LED, D);
          LCD();
//          S = digitalRead(2);
//          if (S == HIGH) {
//            t=tmax;
//          }
          if (temperature > Tmax) {
            digitalWrite(Magnet, LOW);
  			t = tmax;
          }
      
      }

      digitalWrite(Magnet, LOW);
                 
}

void Drehschalter() {
          Grades = analogRead(0);
          if (Grades >= 0 && Grades <= 205) {
            tmax = 10000;
            }
          if (Grades > 205 && Grades <= 410) {
            tmax = 20000;
            }
          if (Grades > 410 && Grades <= 615) {
            tmax = 30000;
            }
          if (Grades > 615 && Grades <= 820) {
            tmax = 40000;
            }
          if (Grades > 820 && Grades <= 1024) {
            tmax = 50000;
            }
}

void LCD() {
          lcd.setCursor(0, 0);
          lcd.print("T=");
          lcd.print(temperature);
          lcd.print("`C ");
          lcd.print("t=");
          lcd.print(t/1000);
          lcd.print("s");
          lcd.setCursor(0, 1);
          lcd.print("D=");
          lcd.print((D*100)/255);
          lcd.print("% ");
          lcd.print("tmax=");
          lcd.print(tmax/1000);
          lcd.print("s   ");
}

void Abbrechen() {
  digitalWrite(Magnet, LOW);
  t = tmax;
}

