#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_TFTLCD.h> // Hardware-specific library
#include <stdlib.h>
#include <TouchScreen.h>
// SD card
#include <SD.h>
#include <SPI.h>

// The chip select pin for the SD card on the shield
#define SD_CS 5 

// These are the pins for the shield!
#define YP A1  // must be an analog pin, use "An" notation!
#define XM A2  // must be an analog pin, use "An" notation!
#define YM 7   // can be a digital pin
#define XP 6   // can be a digital pin

#define TS_MINX 150
#define TS_MINY 120
#define TS_MAXX 920
#define TS_MAXY 940
#define BOXSIZE 40
#define MINPRESSURE 10
#define MAXPRESSURE 1000

// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it
// For the one we're using, its 300 ohms across the X plate
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);
/*
CharakterBox 5x8 10x16  15x24
*/
// The control pins can connect to any pins but we'll use the 
// analog lines since that means we can double up the pins
// with the touch screen (see the TFT paint example)
#define LCD_CS A3    // Chip Select goes to Analog 3
#define LCD_CD A2    // Command/Data goes to Analog 2
#define LCD_WR A1    // LCD Write goes to Analog 1
#define LCD_RD A0    // LCD Read goes to Analog 0

// you can also just connect RESET to the arduino RESET pin
#define LCD_RESET A4


// Color definitions
#define	BLACK           0x0000
#define	BLUE            0x001F
#define	RED             0xF800
#define	GREEN           0x07E0
#define CYAN            0x07FF
#define MAGENTA         0xF81F
#define YELLOW          0xFFE0 
#define WHITE           0xFFFF
// Ziffern grösse
int JFX = 6;
int JFY = 8;
int JFA = 5;    //Abstand zur Box
// Ausgabe
int zeile_y = 30;
int zeile = 0;
// sensibler Teil
int btn_breit = 80;
int btn_hoehe = 20;
int btn_d = (318-(3*btn_breit))/6;
int btn1_x = btn_d;
int btn2_x = btn1_x*3+ btn_breit;
int btn3_x = btn1_x*5+ 2*btn_breit;
int btn_y = 205;
int btn4_x = btn3_x;
int btn4_y = btn_y - zeile_y*2;
int btn5_x = btn3_x;
int btn5_y = btn_y - zeile_y*4;
int soll_x = btn3_x+20;
int soll_y = btn_y - zeile_y*3;
int ist_x = btn3_x+20;
int ist_y = btn_y - zeile_y*5;
//Status
const int AUS = 0;
const int AN  = 1;
const int AUTO = 2;

int vstatus = AUS;
int astatus = AN;      //sonst zeigt er zuerst nichts an
//Temperatur
int vsoll = 30;
int asoll = 31;
int vist = 0;
int aist = 0;
//Steckdose
int dose = 2;
int vstate = LOW;
// time
unsigned long zeit;
int amin = 0;

Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
/************* HARDWARE SPI ENABLE/DISABLE */
// we want to reuse the pins for the SD card and the TFT - to save 2 pins. this means we have to
// enable the SPI hardware interface whenever accessing the SD card and then disable it when done
int8_t saved_spimode;

void disableSPI(void) {
  saved_spimode = SPCR;
  SPCR = 0;
}

void enableSPI(void) {
  SPCR = saved_spimode; 
}
/******************************************/
/* start ************SD Karte*********************/
File myFile;
void read_SD(){
  Serial.print("Read SD card...");
  enableSPI();
  if (SD.begin(SD_CS)){
   myFile = SD.open("runden.txt");
   if (myFile){
      float decade = pow(10, (myFile.available() - 1));
      Serial.print(myFile.available());
      Serial.print(decade);
      while(myFile.available())
      {
        int temp = (myFile.read() - '0');
      }
      Serial.print("Rennen = ");

      myFile.close();
   } else {
     write_SD(1);
   }  
  } 
  disableSPI();
}

char buffer[6];
void write_SD(int i){
     myFile = SD.open("runden.txt", FILE_WRITE);
    if (myFile) {
      itoa(i,buffer,10);  
  myFile.seek(0);    
      myFile.write(buffer);
            Serial.print(buffer);
            Serial.println(" Writing to runden.txt...");
      myFile.close();
    } else {
      Serial.println("error opening test.txt");
    }       
}
/****************SD Karte****************** ende */
void start_lcd() {
  tft.fillScreen(BLACK);
  tft.setRotation(3);
  tft.setTextSize(2);
  tft.setTextColor(GREEN);
  // Textrahmen
  tft.setCursor(btn1_x,zeile*zeile_y); zeile++;
  tft.print("Jfs Laborsklave");
  tft.setTextSize(1);
  tft.setTextColor(BLUE);
  tft.setCursor(btn1_x,zeile*zeile_y);
  zeile++;
  tft.print("Status Minuten");
  tft.setCursor(btn1_x,zeile*zeile_y); 
  zeile++;
  tft.print("aktuelle Temperatur");
  tft.setCursor(btn1_x,zeile*zeile_y); zeile++;
  //tft.print("schnellste");
  tft.setCursor(btn1_x,zeile*zeile_y); zeile++;
  tft.print("maximale Temperatur");
   tft.setCursor(btn1_x,zeile*zeile_y); zeile++;
  //tft.print("Rennen Nr.");
  // erster Button
  tft.setTextSize(2);
  tft.setTextColor(GREEN);
  tft.drawRect(btn1_x, btn_y  , btn_breit, btn_hoehe, GREEN);
  tft.setCursor(btn1_x+8,btn_y+3); 
  tft.print("An");
  tft.drawRect(btn2_x, btn_y, btn_breit, btn_hoehe, GREEN);
  tft.setCursor(btn2_x+8,btn_y+3); 
  tft.print("Aus");  
  tft.drawRect(btn3_x, btn_y, btn_breit, btn_hoehe, GREEN); 
  tft.setCursor(btn3_x+8,btn_y+3); 
  tft.print("Auto");
  tft.drawRect(btn4_x, btn4_y, btn_breit, btn_hoehe, BLUE); 
  tft.setCursor(btn4_x+28,btn4_y+3); 
  tft.print("+");
  tft.drawRect(btn5_x, btn5_y, btn_breit, btn_hoehe, BLUE); 
  tft.setCursor(btn5_x+28,btn5_y+3); 
  tft.print("-");

}

void shwint(int x,int y,int sizech,int stellen,int i,int color,boolean r) {
  String s = String(i);
  int l = s.length();  
  if (r==true) tft.drawRect(x-sizech,y-sizech,stellen*sizech*JFX+sizech*2,sizech*JFY+sizech*2,color);
  tft.fillRect(x,y,stellen*sizech*JFX,sizech*JFY,BLACK);
  tft.setTextColor(color);
  tft.setTextSize(sizech);
  int v = 1;
  for (int c =l-1; c>=0; c--){
      int d = (stellen-v)*sizech*JFX;
      tft.setCursor(x+d,y);
      tft.print(s.charAt(c));
      v++;
  }
}

void shwstr(int x,int y,int sizech,int stellen,String s,int color,boolean r) {
//  String s = String(i);
  int l = s.length();  
  if (r==true) tft.drawRect(x-sizech,y-sizech,stellen*sizech*JFX+sizech*2,sizech*JFY+sizech*2,color);
  tft.fillRect(x,y,stellen*sizech*JFX,sizech*JFY,BLACK);
  tft.setTextColor(color);
  tft.setTextSize(sizech);
  int v = 1;
  for (int c =l-1; c>=0; c--){
      int d = (stellen-v)*sizech*JFX;
      tft.setCursor(x+d,y);
      tft.print(s.charAt(c));
      v++;
  }
}
void shwtime(){
    
}
void setup(void) {
  Serial.begin(115200);
  Serial.println("8 Bit LCD test!");
  pinMode(dose, OUTPUT);
  tft.reset();
  uint16_t identifier = tft.readID();
  tft.begin(identifier);
  read_SD();
  start_lcd();

}

double Thermistor(int RawADC) {
 double Temp;
 Temp = log(10000.0*((1024.0/RawADC-1)));
//         =log(10000.0/(1024.0/RawADC-1)) // for pull-up configuration
 Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
 Temp = Temp - 273.15;            // Convert Kelvin to Celcius
//Temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
 return Temp;
}
void shwsoll(){
  shwint(soll_x,soll_y,2,4,vsoll,BLUE,false);  
} 

  
void shwstatus() {
  String s ;
  switch (vstatus){
    case AN:
        s = "AN";
        digitalWrite(dose,HIGH);
     break;
    case AUS:
        s = "AUS";
      digitalWrite(dose,LOW);
    break;
    case AUTO:
       s = "AUTO";
       digitalWrite(dose,HIGH);
   break;  
  }
  shwstr(btn2_x,zeile_y+1,3,4,s,RED,false);
 
}
void shwist(){
   vist = int(Thermistor(analogRead(5)));
   shwint(ist_x,ist_y,2,4,vist,RED,false);  
}
void loop(void) {
  if (astatus != vstatus) {  
    shwstatus();
    astatus = vstatus;
  }
  if (asoll != vsoll) {
    shwsoll();
    asoll = vsoll;
  } 
  vist = int(Thermistor(analogRead(5)));
    if (aist != vist) {
    shwist();
    aist = vist;
  } 
  if (vstatus == AUTO){
    if (vist>=vsoll){
     digitalWrite(dose,LOW);
     vstatus= AUS;
     }  
    long int now = (millis() - zeit)/60000;
    int vmin = int(now);
    if (amin != vmin) { 
     shwint(ist_x,ist_y-zeile_y,2,4,vmin,GREEN,false);  
     amin = vmin;
    }
  }
  Serial.println(int(Thermistor(analogRead(5))));  // display Fahrenheit
  digitalWrite(13, HIGH);
  Point p = ts.getPoint();
  digitalWrite(13, LOW);
  // if you're sharing pins, you'll need to fix the directions of the touchscreen pins!
  //pinMode(XP, OUTPUT);
  pinMode(XM, OUTPUT);
  pinMode(YP, OUTPUT);
  //pinMode(YM, OUTPUT);
  // we have some minimum pressure we consider 'valid'
  // pressure of 0 means no pressing!
  if (p.z > MINPRESSURE && p.z < MAXPRESSURE) {
    int x = map(p.y, TS_MINY, TS_MAXY, 0,tft.width());
    int y = map(p.x, TS_MINX, TS_MAXX, tft.height(),0);
    Serial.print(btn4_y);
    Serial.print("  ");
    Serial.print(btn4_y +btn_hoehe);
    Serial.print(" x ");
    Serial.print(x);
    Serial.print(" y ");
    Serial.println(y);
    
    
    if (y > btn_y){
      if (( x > btn1_x) && (x < btn1_x+btn_breit)){ //Start
           Serial.println("An");  
           vstatus = AN;     
      }
      if (( x > btn2_x) && (x < btn2_x+btn_breit)){ //Stop
           Serial.println("Aus");     
           vstatus = AUS;  
      }
      if (( x > btn3_x) && (x < btn3_x+btn_breit)){ //Save
           Serial.println("Auto");  
           vstatus =AUTO;
           zeit = millis();      
      }       
    }
    if ((x > btn4_x) && (x< btn4_x+btn_breit)){
        if (( y < btn4_y+30) && (y > btn4_y-10)){
          vsoll++;
          delay(500);
      }
      if ((x > btn5_x) && (x< btn5_x+btn_breit)){
        if (( y < btn5_y+30) && (y > btn5_y-10)){
          vsoll--;
          delay(500);
      }
      }
    }  
  }
}

