#include <LiquidCrystalFast.h>      //include LCD library
#include <SPI.h>                    //include SPI library
#include <SD.h>                     //include SD card library
#include <EEPROM.h>                 //include EEPROM library
#define TIME_100ms 40535            //casovac 1, cas: 100ms pri 16MHz crystalu
#define maxOffset 100;
#define minOffset 0;
#define updowndebounce 400;

// mapovani sondy c.1
#define IN1 A9
#define TERM1 A10
#define ID1 A11
#define DET1 29
#define VENT1 25

// mapovani sondy c.2
#define IN2 A6
#define TERM2 A8
#define ID2 A7
#define DET2 28
#define VENT2 24

// mapovani sondy c.3
#define IN3 A4
#define TERM3 A5
#define ID3 A3
#define DET3 27
#define VENT3 23

// mapovani sondy c.4
#define IN4 A1
#define TERM4 A2
#define ID4 A0
#define DET4 26
#define VENT4 22

//definovani ostatnich promennych
#define Vcc13 A13
#define voltage3 A14
#define TERM A15
#define PWMOUT 46
#define ManualReset 48
#define WDI 49

//define LCD pins
# define RS 39
#define RW 21 //- not use
#define E1 70
#define E2 73
#define BackLight 71      //PJ3
#define DB4 14
#define DB5 15
#define DB6 74
#define DB7 72
LiquidCrystalFast lcd(RS, 255, E1, E2, DB4, DB5, DB6, DB7);   //initialize LCD with LCD library
//LiquidCrystal lcd(RS,RW,Enable1,Enable2, data3,data2,data1,data0);

//define buttons
#define TL1 38
#define TL2 41
#define TL3 40
#define TL4 78
#define TL5 7
#define TL6 77
#define TL7 79
#define TL8 76
#define TL9 32
#define TL10 33
#define TL11 35
#define TL12 37

// LEDs
#define ERROR_LED 81
#define LED1 16
#define LED2 6
#define LED3 3
#define LED4 5
#define LEDTL1 2
#define LEDTL3 82
#define LEDTL5 80
#define LEDTL7 17
#define LEDTL9 31
#define LEDTL10 30 
#define LEDTL11 34
#define LEDTL12 36
#define buzzer 8
#define SS 53                        // for SD card
Sd2Card card;  
SdVolume volume;
SdFile root;

//               {-80   -70, -65, -60,  -55,  -50,  -45,  -40,   -30,  -20,   -10,    0,   10,   13,  14                   };   vykon v dBm na 50MHz
int kaladc[4][15]={{20,  30,  35,  40,   45,   50,   55,   60,    70,   80,    90,   100,  110,  113, 114},            //dBm input-100
                  {119, 188, 239, 292,  340,  392,  444,  493,   594,  696,   793,  899,  1002,  1023, 1024},          //for AD8307 for 50 MHz
                  {208, 216, 231, 258,  297,  335,  374,  412,   489,  566,   643,  705,  705,  706, 706},           //for AD8313 opravit for 1GHz
                  {158, 172, 195, 233,  280,  327,  374,  422,   519,  615,   717,  788,  795,  795, 795}};          //for AD8318 for 2 GHz
int kalfreq[6][11]= {{3,    10,   20,   30,   50,   100,  200, 300,  400,  500,  600},                                 //frek AD8307 by 0dBm
                    { 100,  144,  470,  900,  1000,  1300, 1500, 1800, 1900,  2300,  2500},                      //frek AD8313 by -10dBm
                    { 100,   470,  890, 1900, 3000, 3500, 4000,  5000, 6000,  7000,  8000},                             //frek AD8318 by -10dBm
                    { -8,    -6,   -4,    -2,   0,      8  , 22,   38,   59,   82,  125},                                  //frek offset for AD8307
                    { 8,    6,   0,    -3,    0,     -4  , -23,   -56,   -61,   -39,  -24},                                  //frek offset for AD8313
                    { 46,    40,  33,   3,    -3,    15  , 37,    66,   90,     144,  152}};                                 //frek offset for AD8318

unsigned char frekChan[4]={0,0,0,0};
float offset[4]={0,0,0,0};
unsigned char TL8_press=0, TL6_press=0;
unsigned long cas=0;
int adresaEEPROM;
byte degree[8] =    // create ° char
{ B01100,
  B10010,
  B10010,
  B01100,
  B00000,
  B00000,
  B00000,
  B00000  };

int readingTERM,readingTERM1,readingTERM2,readingTERM3,readingTERM4, command; 
const byte pocetPrumerovani  = 10;
const byte pocetPrumerovani1 = 10;
const byte pocetPrumerovani2 = 10;
const byte pocetPrumerovani3 = 10;
int readings[pocetPrumerovani];   // the readings from the analog input
int readings1[pocetPrumerovani1];
int readings2[pocetPrumerovani2];
int readings3[pocetPrumerovani3];
unsigned char index=0,index1=0,index2=0,index3=0;                  // the index of the current reading
int total=0,total1=0,total2=0,total3=0;                            // the running total
int average=0,average1=0,average2=0,average3=0;                    // the average
int prum1,prum2,prum3,prum4;
int PWMvalue, reading12V;
unsigned char pomPWM,pomTL5,pomVcc,FREK_OFFSET,pomPSW=0,pomVypis=0,pomVypPSQV=0,c;
char znak;
float rho,P1,P2,PSV;

float calculateValue(unsigned char typsondy, int hodnotaAD,unsigned char frekvence)
{
  int k, p;
  float v,vysl;
  int adcValue;
  if (typsondy<1 || typsondy>3){return -300;}
  if (frekvence<0 || frekvence>10){return -100;}
  unsigned char c;
  adcValue=hodnotaAD+kalfreq[typsondy+2][frekvence];
      for (c=0; c<15;c++)                                      
      {
        if (adcValue<=kaladc[typsondy][c])
        {
          break;
        }
      }
      if (c>12) 
      {
        c=13;
      }    
      if (c<1) c=1;
      k=((kaladc[typsondy][c])-(kaladc[typsondy][c-1]));		// výpočet výkonu podle podobnosti trojúhelníku UPRAVENO BOBEM
      p=((kaladc[0][c])-(kaladc[0][c-1]));
      v= adcValue-kaladc[typsondy][c-1];
      vysl=((p*v)/k)+kaladc[0][c-1]-100;
      return vysl;
}
float powerConversion(float zmerenedBm, char *jednotka)
{
      float outPower;
      float nasobek;
      if(zmerenedBm < -60)
      {
        *jednotka='p';
        nasobek=1e9;
      }
      else if (zmerenedBm < -30)
      {
        *jednotka='n';
        nasobek=1e6;

      }
      else if
      (zmerenedBm < 0)
      {
        *jednotka='u';
        nasobek=1e3;

      }
      else if
      (zmerenedBm < 30)
      {
        *jednotka='m';
        nasobek=1;
      }
      else if
      (zmerenedBm <=60)
      {
        *jednotka=' ';
        nasobek=1e-3;

      }
      else if
      (zmerenedBm > 60)
      {
        *jednotka='k';
        nasobek=1e-6;
      }
      
      outPower =(pow(10,zmerenedBm/10)*nasobek);
      return outPower;
}

void setup() {
  lcd.begin(40, 4);                                    //set LCD columns and rows
  //define INPUT pins  
  PORTH=0xFF;                                         //PORTH is OFF - LEDs
  PORTC=0xFF;                                         //PORTC is OFF - LEDs
  PORTD=0xFF;                                         //PORTD is OFF - LEDs     
  PORTE=0xFF;                                         //PORTE is OFF - LEDs 
  //define INPUT/OUTPUT pins
  DDRA|= (0<<PA7)|(0<<PA6)|(0<<PA5)|(0<<PA4)|(1<<PA3)|(1<<PA2)|(1<<PA1)|(1<<PA0);        // DETECTION SOND + FANs
  DDRC|= (1<<PC7)|(1<<PC6)|(0<<PC5)|(0<<PC4)|(1<<PC3)|(0<<PC2)|(1<<PC1)|(0<<PC0);
  DDRD|= (0<<PD7)|(0<<PD6)|(0<<PD5)|(0<<PD4);
  DDRE|= (1<<PE7)|(1<<PE6)|(1<<PE5)|(1<<PE4)|(1<<PE3)|(1<<PE2);
  DDRF|= (0<<PF7)|(0<<PF6)|(0<<PF5)|(0<<PF4)|(0<<PF3)|(0<<PF2)|(0<<PF1)|(0<<PF0);       //A/D converters
  DDRG|= (0<<PG1)|(0<<PG0);
  DDRH|= (1<<PH5)|(0<<PH4)|(1<<PH3)|(0<<PH2)|(1<<PH1)|(1<<PH0);
  DDRJ|= (1<<PJ3);
  DDRK|= (0<<PK7)|(0<<PK6)|(0<<PK5)|(0<<PK4)|(0<<PK3)|(0<<PK2)|(0<<PK1)|(0<<PK0);       //A/D converters
  
  pinMode(SS, OUTPUT);                                 // Chip select for SD card define as output pin
  pinMode(PWMOUT, OUTPUT);
  digitalWrite(PWMOUT,LOW);
  PORTJ=(1<<PJ3);                                      //Backlight On  
  Serial.begin(9600);
  digitalWrite(buzzer, LOW);    // bleeping in begin
  delay(50);  
  digitalWrite(buzzer, HIGH);
  delay(50);
  digitalWrite(buzzer, LOW);
  delay(50);
  digitalWrite(buzzer,HIGH);
  lcd.createChar(0,degree);
  lcd.clear();                                              //clear LCD    
  analogReference(EXTERNAL);                                // choice external voltage reference for A/D converters = 2.5 V   
  lcd.setCursor(4,0);
  lcd.print("OK2LZ");
  lcd.setCursor(29,0);
  lcd.print("Dcom, s.r.o");
  lcd.setCursor(13,1);
  lcd.print("RF power meter");
  lcd.setCursor(18,2);
  lcd.print("v1.0");
  lcd.setCursor(0,3);
  lcd.print("3V3: ");
  int reading3V3 = analogRead(voltage3);                    //3V3 reading
  lcd.print(((reading3V3*2.5/1024)/712)*1000);
  lcd.print("V");
  lcd.setCursor(14,3);
  lcd.print("Ucc:");
  int reading12V = analogRead(Vcc13);                        //12V reading
  lcd.print(((reading12V*2.5/1024)/17)*100);
  lcd.print("V");
  lcd.setCursor(28,3);
  lcd.print("Temp: ");
  readingTERM = analogRead(TERM);
  //lcd.print(140-(0.1774*readingTERM),1);      //puvodni
  lcd.print(177-(0.23*readingTERM),1);      //nove
  lcd.write(byte(0));        //create degree symbol from memory
  lcd.print("C");
  int x = 1;
  for (int i = 0; i > -1; i = i + x){
    analogWrite(PWMOUT, i);
    if (i == 130) x = -1;             // switch direction at peak
    delay(8);
  }  

  if (!card.init(SPI_HALF_SPEED, SS))   
  {
    digitalWrite(ERROR_LED,LOW);                          // error LED on
    digitalWrite(buzzer, LOW);                            // bleeping error
    delay(200);
    digitalWrite(LEDTL7, LOW);
    digitalWrite(buzzer, HIGH);
    delay(200);
    digitalWrite(buzzer, LOW);
    digitalWrite(LEDTL7, HIGH);
    delay(200);
    digitalWrite(LEDTL7, LOW);
    digitalWrite(buzzer,HIGH);
    lcd.clear();
    lcd.setCursor(10,0);
    lcd.print("Card is not inserted.");
    lcd.setCursor(10,2);
    lcd.print("Please insert SD card....");
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card is inserted?");
    delay(3000);
  }
  delay(2500);
  lcd.clear();
}

unsigned char det1, det2, det3, det4,sondadet1=0,b=0,a=0,   d,sondadet2=0,e,   f,sondadet3=0,    h,sondadet4=0;
int adcID1,adcID2,adcID3,adcID4,adcTERM1,adcTERM2,adcTERM3,adcTERM4,adcIN1,adcIN2,adcIN3,adcIN4;
unsigned char pomLCD=0,selChan=0;
 


void loop() {
  float outval;
  float POWER;
  // put your main code here, to run repeatedly: 
  det1 = digitalRead(DET1);
  det2 = digitalRead(DET2);
  det3 = digitalRead(DET3);
  det4 = digitalRead(DET4);
  adcID1=analogRead(ID1);
  adcID2=analogRead(ID2); 
  adcID3=analogRead(ID3); 
  adcID4=analogRead(ID4);
  adcTERM1=analogRead(TERM1);
  adcTERM2=analogRead(TERM2);
  adcTERM3=analogRead(TERM3);
  adcTERM4=analogRead(TERM4);
  //adcIN1=analogRead(IN1);
  // adcIN2=analogRead(IN2);
  adcIN3=analogRead(IN3);
  adcIN4=analogRead(IN4);

  //calculate Averages of 4 channels

  total= total - readings[index];        
  readings[index] = analogRead(IN1);
  total= total + readings[index];      
  index = index + 1;                    
  if (index >= pocetPrumerovani | index1 >= pocetPrumerovani)              
  {
    index = 0;                          
    prum1 = total / pocetPrumerovani; 
  }

  total1= total1 - readings1[index1];        
  readings1[index1] = analogRead(IN2);
  total1= total1 + readings1[index1];      
  index1 = index1 + 1;                    
  if (index1 >= pocetPrumerovani | index1 >= pocetPrumerovani)              
  {
    index1 = 0;                          
    prum2 = total1 / pocetPrumerovani; 
  }

  total2= total2 - readings2[index2];        
  readings2[index2] = analogRead(IN3);
  total2= total2 + readings2[index2];      
  index2 = index2 + 1;                    
  if (index2 >= pocetPrumerovani2 | index2 >= pocetPrumerovani2)              
  {
    index2 = 0;                          
    prum3 = total2 / pocetPrumerovani; 
  }

  total3= total3 - readings3[index3];        
  readings3[index3] = analogRead(IN4);
  total3= total3 + readings3[index3];      
  index3 = index3 + 1;                    
  if (index3 >= pocetPrumerovani3 | index3 >= pocetPrumerovani3)              
  {
    index3 = 0;                          
    prum4 = total3 / pocetPrumerovani; 
  }




  if (det1==1)
  {
    if(pomLCD==1)
    {
      lcd.clear();
      pomLCD=0;
    }
    digitalWrite(LED1, LOW);
    if (a==0)
    {
      digitalWrite(buzzer, LOW);    // bleeping 
      delay(50);  
      digitalWrite(buzzer, HIGH);
      delay(50);
      a=1;
    }
    lcd.setCursor(0,0);
    if (adcID1 >= 540 & adcID1 <= 570)
    {  
      lcd.print("AD8307");
      sondadet1=1;
    }
    if(adcID1 >= 750 & adcID1 <= 780)
    {
      lcd.setCursor(0,0);
      lcd.print("AD8313");
      sondadet1=2;
    }
    if(adcID1 >= 800 & adcID1 <= 830)
    {
      lcd.setCursor(0,0);
      lcd.print("AD8318"); 
      sondadet1=3;
    }
    if(adcID1 > 830 | adcID1 < 540)
    {
      lcd.setCursor(0,0);
      lcd.print("NEZNAM");
      sondadet1=0;
    }

    lcd.setCursor(0,1);
    lcd.print(" ");
    if (sondadet1>0 && sondadet1<4)
    {
      if (FREK_OFFSET==0)
      {
      lcd.print(kalfreq[sondadet1-1][frekChan[0]]);
      lcd.print("MHz  ");
      }
      else 
      lcd.print(offset[0]);
      lcd.print("  ");
      outval=calculateValue(sondadet1,prum1,frekChan[0]);
      outval+=offset[0];
      lcd.setCursor(0,2);
      lcd.print(outval,1);
      lcd.print("dBm ");
     // Serial.println(outval);
      lcd.setCursor(0,3);
      POWER = powerConversion(outval,&znak);                                //conversion from dBm to mW ??
      P1=powerConversion(outval,&znak);
      lcd.print(POWER);
      lcd.print(znak);
      lcd.print("W ");
   }

  }

  else
  {
    digitalWrite(LED1, HIGH);
    digitalWrite(LEDTL9,HIGH);
    if(sondadet1)
    {
      lcd.clear();
      sondadet1=0;
    }
  
}

 if (det2==1)
  {
    if(pomLCD==1)
    {
      lcd.clear();
      pomLCD=0;
    }
    digitalWrite(LED2, LOW);
    if (d==0)
    {
      digitalWrite(buzzer, LOW);    // bleeping 
      delay(50);  
      digitalWrite(buzzer, HIGH);
      delay(50);
      d=1;
    }
    lcd.setCursor(9,0);
    if (adcID2 >= 540 & adcID2 <= 570)
    {  
      lcd.print("AD8307");
      sondadet2=1;
    }
    if(adcID2 >= 750 & adcID2 <= 780)
    {
      lcd.setCursor(9,0);
      lcd.print("AD8313");
      sondadet2=2;
    }
    if(adcID2 >= 800 & adcID2 <= 830)
    {
      lcd.setCursor(9,0);
      lcd.print("AD8318"); 
      sondadet2=3;
    }
    if(adcID2 > 830 | adcID2 < 540)
    {
      lcd.setCursor(9,0);
      lcd.print("NEZNAM");
      sondadet2=0;
    }

    lcd.setCursor(10,1);
    lcd.print(" ");
    if (sondadet2>0 && sondadet2<4)
    {
      if (FREK_OFFSET==0)
      {lcd.print(kalfreq[sondadet2-1][frekChan[1]]);
      lcd.print("MHz  ");
      }
      else
      lcd.print(offset[1]);
      lcd.print("  ");
      outval=calculateValue(sondadet2,prum2,frekChan[1]);
      outval+=offset[1];
      lcd.setCursor(10,2);
      lcd.print(outval,1);
      lcd.print("dBm ");
      //Serial.println(outval);
      lcd.setCursor(10,3);
      POWER = powerConversion(outval,&znak);                                //conversion from dBm to mW ??
      P2=powerConversion(outval,&znak);  
      lcd.print(POWER);
      lcd.print(znak);
      lcd.print("W ");
    
    }

  }

  else
  {
    digitalWrite(LED2, HIGH);
    digitalWrite(LEDTL10,HIGH);
    if(sondadet2)
    {
      lcd.clear();
      sondadet2=0;
    }
  }



 if (det3==1)
  {
    if(pomLCD==1)
    {
      lcd.clear();
      pomLCD=0;
    }
    digitalWrite(LED3, LOW);
    if (f==0)
    {
      digitalWrite(buzzer, LOW);    // bleeping 
      delay(50);  
      digitalWrite(buzzer, HIGH);
      delay(50);
      f=1;
    }
    lcd.setCursor(21,0);
    if (adcID3 >= 540 & adcID3 <= 570)
    {  
      lcd.print("AD8307");
      sondadet3=1;
    }
    if(adcID3 >= 750 & adcID3 <= 780)
    {
      lcd.setCursor(21,0);
      lcd.print("AD8313");
      sondadet3=2;
    }
    if(adcID3 >= 800 & adcID3 <= 830)
    {
      lcd.setCursor(21,0);
      lcd.print("AD8318"); 
      sondadet3=3;
    }
    if(adcID3 > 830 | adcID3 < 540)
    {
      lcd.setCursor(21,0);
      lcd.print("NEZNAM");
      sondadet3=0;
    }

    lcd.setCursor(21,1);
    lcd.print(" ");
    if (sondadet3>0 && sondadet3<4)
    { if (FREK_OFFSET==0)
      {lcd.print(kalfreq[sondadet3-1][frekChan[2]]);
      lcd.print("MHz  ");}
      else
      lcd.print(offset[2]);
      lcd.print(" ");
      outval=calculateValue(sondadet3,prum3,frekChan[2]);
      outval+=offset[2];
      lcd.setCursor(21,2);
      lcd.print(outval,1);
      lcd.print("dBm ");
      //Serial.println(outval);
      lcd.setCursor(21,3);
      POWER = powerConversion(outval,&znak);                                //conversion from dBm to mW ??
      lcd.print(POWER);
      lcd.print(znak);
      lcd.print("W ");
    }

  }

  else
  {
    digitalWrite(LED3, HIGH);
    digitalWrite(LEDTL11,HIGH);
    if(sondadet3)
    {
      lcd.clear();
      sondadet3=0;
    }
  }
  
  
 if (det4==1)
  {
    if(pomLCD==1)
    {
      lcd.clear();
      pomLCD=0;
    }
    digitalWrite(LED4, LOW);
    if (h==0)                                                  //opravdu  h ???
    {
      digitalWrite(buzzer, LOW);    // bleeping 
      delay(50);  
      digitalWrite(buzzer, HIGH);
      delay(50);
      h=1;
    }
    lcd.setCursor(32,0);
    if (adcID4 >= 540 & adcID4 <= 570)
    {  
      lcd.print("AD8307");
      sondadet4=1;
    }
    if(adcID4 >= 750 & adcID4 <= 780)
    {
      lcd.setCursor(32,0);
      lcd.print("AD8313");
      sondadet4=2;
    }
    if(adcID4 >= 800 & adcID4 <= 830)
    {
      lcd.setCursor(32,0);
      lcd.print("AD8318"); 
      sondadet4=3;
    }
    if(adcID4 > 830 | adcID4 < 540)
    {
      lcd.setCursor(32,0);
      lcd.print("NEZNAM");
      sondadet4=0;
    }

    lcd.setCursor(32,1);
    lcd.print(" ");
    if (sondadet4>0 && sondadet4<4)
    { if (FREK_OFFSET==0)
      {lcd.print(kalfreq[sondadet4-1][frekChan[3]]);
      lcd.print("MHz  ");}
      else
      lcd.print(offset[3]);
      lcd.print("  ");
      outval=calculateValue(sondadet4,prum4,frekChan[3]);
      outval+=offset[3];
      lcd.setCursor(32,2);
      lcd.print(outval,1);
      //Serial.println(outval);
      lcd.print("dBm ");
      lcd.setCursor(32,3);
      POWER = powerConversion(outval,&znak);                                //conversion from dBm to mW ??
      lcd.print(POWER);
      lcd.print(znak);
      lcd.print("W ");
     
    }

  }

  else
  {
    digitalWrite(LED4, HIGH);
    digitalWrite(LEDTL12,HIGH); 
    if(sondadet4)
    {
      lcd.clear();
      sondadet4=0;
    }
  }


  if (digitalRead(TL9)==0 && sondadet1)
  {
    selChan=0;
    digitalWrite(LEDTL9,LOW);
    digitalWrite(LEDTL10,HIGH);
    digitalWrite(LEDTL11,HIGH);
    digitalWrite(LEDTL12,HIGH);
    Serial.println("Vybran kanal c.1");
   }
  else
  if (digitalRead(TL10)==0 && sondadet2)
  {
    selChan=1;
    digitalWrite(LEDTL9,HIGH);
    digitalWrite(LEDTL10,LOW);
    digitalWrite(LEDTL11,HIGH);
    digitalWrite(LEDTL12,HIGH);
    Serial.println("Vybran kanal c.2");
  }
  else
  if (digitalRead(TL11)==0 && sondadet3)
  {
    selChan=2;
    digitalWrite(LEDTL9,HIGH);
    digitalWrite(LEDTL10,HIGH);
    digitalWrite(LEDTL11,LOW);
    digitalWrite(LEDTL12,HIGH);
    Serial.println("Vybran kanal c.3");
  }
  else
  if (digitalRead(TL12)==0 && sondadet4 )
  {
    selChan=3;
    digitalWrite(LEDTL9,HIGH);
    digitalWrite(LEDTL10,HIGH);
    digitalWrite(LEDTL11,HIGH);
    digitalWrite(LEDTL12,LOW);
    Serial.println("Vybran kanal c.4");
    
  }
  
  
  if (digitalRead(TL1) == 0)                                   // MENU (TL1)
  { 
    digitalWrite(LEDTL1, LOW);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("PSV");
    lcd.setCursor(0,1);
    lcd.print("BackLig");
    delay(1000);
    digitalWrite(LEDTL1, HIGH);
    if(digitalRead(TL4) == 0)
    {
      if(digitalRead(BackLight) == 1)
      {
        PORTJ=(0<<PJ3);
      }
      else
      {
        PORTJ=(1<<PJ3);
      }
    } 
         
    if(digitalRead(TL2) == 1)
      {
        pomPSW=0;
      
      }
      else
      {
        pomPSW=1;
      }
    
   lcd.clear();
   pomLCD=0;
  }
  

  if (digitalRead(TL2) == 0)                                   // Frekquency UP(TL2)
  {  
    frekChan[selChan]++;
    FREK_OFFSET=0;

    if (frekChan[selChan]>=11)
    {
      frekChan[selChan]=0;
    }
    delay(150);                                               //debounce time (150ms)
  }
  
if (frekChan[selChan]>=10)
    {
      frekChan[selChan]=10;
    }

  if (digitalRead(TL3) == 0)                                   // PWM (TL3)
  {
    
    if(pomPWM==0)
    {
      pomPWM=1;
      
    }
    else
      pomPWM=0;
      
     delay(200);   
  }


  if (digitalRead(TL4) == 0)                                   // Frekquency DOWN (TL4)                   
  {  
    frekChan[selChan]--;
    FREK_OFFSET=0;

    if (frekChan[selChan]>=0xFF)
    {
      frekChan[selChan]=10;
    }
    delay(150);                                                                //debounce time (150ms)
  }
  
if (digitalRead(TL6)==0 && TL6_press == 0)
 {
   TL6_press=1;
   FREK_OFFSET=1;

   cas=millis();
   offset[selChan]+=0.1;
  if (offset[selChan] > 100)
   {
     offset[selChan] = maxOffset;
   } 
 }
if ((digitalRead(TL6)==0)&&(TL6_press==1) && (millis()-cas>400))
 {  
   cas=millis();
 //  TL6_press=0;
   offset[selChan]+=1;
   if (offset[selChan]>100)
    {
      offset[selChan]=maxOffset;
    }
 }
 if (digitalRead(TL6)==1)
  {
    TL6_press=0;
    delay(50);
  }
 ///////////////////////////////////////////////////////////////
  if (digitalRead(TL8)==0 && TL8_press == 0)
 { 
   TL8_press=1;  
   FREK_OFFSET=1;   
   cas=millis();
   offset[selChan]-=0.1;
   if (offset[selChan]<0)
    {
      offset[selChan]=0;
    }
  }
 if ((digitalRead(TL8)==0)&&(TL8_press==1) && (millis()-cas>400))
 {  
   cas=millis();
   // TL8_press=0;
   offset[selChan]-=1;
   if (offset[selChan]<0)
    {
      offset[selChan]=0;
    }
  //delay(150); 
 }
 if (digitalRead(TL8)==1)
  {
    TL8_press=0;
    delay(50);
  }
 


  if (digitalRead(TL5)==0)                                                      //INFO (TL5)
  {
    lcd.clear();
    digitalWrite(LEDTL5, LOW);
    lcd.print("   Vladimir Hradnansky, OK2LZ, 2014");
    lcd.setCursor(0,1);
    lcd.print("3V3: ");
    int reading3V3 = analogRead(voltage3);                                     //3V3 reading
    lcd.print(((reading3V3*2.5/1024)/712)*1000);
    lcd.print("V");
    Serial.print("3V3: ");
    Serial.print(((reading3V3*2.5/1024)/712)*1000);
    Serial.println("V");
    lcd.setCursor(0,2);
    lcd.print("Ucc: ");
    int reading12V = analogRead(Vcc13);                                        //12V reading
    lcd.print(((reading12V*2.5/1024)/17)*100);
    lcd.print("V");
    Serial.print("Ucc: ");
    Serial.print(((reading12V*2.5/1024)/17)*100);
    Serial.println("V");
    lcd.setCursor(0,3);
    lcd.print("Temp: ");
    readingTERM = analogRead(TERM);
    lcd.print(140-(0.1774*readingTERM),1);
    lcd.write(byte(0));                                                        //create degree symbol from memory
    lcd.print("C"); 
    Serial.print("temp:");
    Serial.print(140-(0.1774*readingTERM));
    Serial.println(" st Celsia");
    delay(3000);
    lcd.clear();
    /*
    lcd.print("CH1:");
    lcd.print(sondadet1);
    lcd.print("  ");
    readingTERM1 = analogRead(TERM1);
    lcd.print(140-(0.1774*readingTERM1),1);
    lcd.write(byte(0));                                                        //create degree symbol from memory
    lcd.print(" st Celsia");
    lcd.print("  ADC: ");
    lcd.print(adcIN1);
    lcd.print("  Power:");
  //  lcd.print(vysl,1);
    lcd.setCursor(0,1);
    lcd.print("CH2:");
    lcd.print(sondadet2);
    lcd.print("  ");
    readingTERM2 = analogRead(TERM2);
    lcd.print(140-(0.1774*readingTERM2),1);
    lcd.write(byte(0));                                                        //create degree symbol from memory
    lcd.print("C");
    lcd.print("  ADC: ");
    lcd.print(adcIN2);
    lcd.print("  Power:");
   // lcd.print(vysl2,1);
    lcd.setCursor(0,2);
    lcd.print("CH3:");
    lcd.print(sondadet3);
    lcd.print("  ");
    readingTERM3 = analogRead(TERM3);
    lcd.print(140-(0.1774*readingTERM3),1);
    lcd.write(byte(0));                                                        //create degree symbol from memory
    lcd.print("C");
    lcd.print("  ADC: ");
    lcd.print(adcIN3);
    lcd.print("  Power:");
   // lcd.print(vysl3,1);
    lcd.setCursor(0,3);
    lcd.print("CH4:");
    lcd.print(sondadet4);
    lcd.print("  ");
    readingTERM4 = analogRead(TERM4);
    lcd.print(140-(0.1774*readingTERM4),1);
    lcd.write(byte(0));                                                        //create degree symbol from memory
    lcd.print("C");
    lcd.print("  ADC: ");
    lcd.print(adcIN4);
    lcd.print("  Power:");
  //  lcd.print(vysl4,1);
  
    delay(4000);
    lcd.clear();
    */
    digitalWrite(LEDTL5, HIGH);
    pomLCD=0;
    
  }




  if (digitalRead(TL7) == 0)                                   //if TL7 is pressed, (SD card INFO)
  {  
    lcd.clear();  
    digitalWrite(LEDTL7, LOW);                             // LEDTL7 ON
    {
      if (!card.init(SPI_HALF_SPEED, SS))   
      {
        lcd.setCursor(10,0);
        lcd.print("Card is not inserted.");
        lcd.setCursor(10,2);
        lcd.print("Please insert SD card....");
        Serial.println("initialization failed. Things to check:");
        Serial.println("* is a card is inserted?");
        delay(3000);
        lcd.clear();
        digitalWrite(LEDTL7, HIGH);
        return;
      }
      else 
      {
        Serial.println("Card is inserted.");
        lcd.setCursor(13,0);
        lcd.print("Card is insert.");
        Serial.print("Card type: ");
        lcd.setCursor(0,1);
        lcd.print("Card type: ");
        switch(card.type()) {
        case SD_CARD_TYPE_SD1:
          Serial.println("SD1");
          lcd.print("SD1");
          break;
        case SD_CARD_TYPE_SD2:
          Serial.println("SD2");
          lcd.print("SD2");
          break;
        case SD_CARD_TYPE_SDHC:
          Serial.println("SDHC");
          lcd.print("SDHC");
          break;
        default:
          Serial.println("Unknown"); 
          lcd.print("Unknown");
        }
      }
      if (!volume.init(card)) 
      {
        Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
        lcd.setCursor(0,2);
        lcd.print("Could not find FAT16/FAT32 partition.");
        lcd.setCursor(0,3);
        lcd.print("Please formate your SD card to FAT system.");
        return;
      }
      uint32_t volumesize;
      Serial.print("Volume type is FAT");
      lcd.setCursor(0,2);
      lcd.print("Volume type is FAT");
      Serial.println(volume.fatType(), DEC);
      lcd.print(volume.fatType(), DEC);
      lcd.setCursor(0,3);
      volumesize = volume.blocksPerCluster();           // clusters are collections of blocks
      volumesize *= volume.clusterCount();              // we'll have a lot of clusters
      volumesize *= 512;                                // SD card blocks are always 512 bytes
      Serial.print("Volume size (bytes): ");
      Serial.println(volumesize);
      Serial.print("Volume size (Kbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);
      Serial.print("Volume size(Mbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);
      lcd.print("Volume size (Mbytes): ");
      lcd.print(volumesize);
      lcd.print(" MB");
      lcd.setCursor(36,0);
      lcd.print("LOAD");
      lcd.setCursor(36,1);
      lcd.print("SAVE");
      delay(2000);
      pomLCD=0;
 
 
      
  if (digitalRead(TL9) == 0)                                   //if TL9 is pressed, (SD load)
      {
        lcd.clear();
    if (!SD.begin(SS)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("Karta inicializovana."); 
lcd.print("Pretahuji kalibrace");
        delay(1000);
        File dataFile = SD.open("Pokus01.txt");
// scanf
 char tmpchar;
 char radek[80];
 int *memptr;
 unsigned char EEdata,EEdata1;
 unsigned int EEint;
 unsigned char x,y=0;
 if (dataFile) {
     memset(radek,0,sizeof(radek));
    while (dataFile.available()) 
    { 
      tmpchar=dataFile.read(); 
     delay(5);
     
      strcat(radek,&tmpchar);
      
      if (tmpchar == '\n')
      {
        sscanf(radek,"%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",kaladc[y][0],kaladc[y][1],kaladc[y][2],kaladc[y][3],kaladc[y][4],kaladc[y][5],
        kaladc[y][6],kaladc[y][7],kaladc[y][8],kaladc[y][9],kaladc[y][10],kaladc[y][11],kaladc[y][12],kaladc[y][13],kaladc[y][14],kaladc[y][15]);
        y++;
        memset(radek,0,sizeof(radek));
        if (y==4)
        {
        break ;}
      }
      dataFile.close();
      memptr=&kaladc[0][0];
   //   for(adresaEEPROM=0;adresaEEPROM<sizeof(kaladc);adresaEEPROM++)
    //  {
      adresaEEPROM=0;
      for(x=0;x<4;x++)
      {
        for(y=0;y<15;y++)
        {
        //lcd.print(kaladc[x][y]);
        //lcd.print(" | ");
        EEPROM.write(adresaEEPROM++,(kaladc[x][y]>>8)&0xFF);
        EEPROM.write(adresaEEPROM++,(kaladc[x][y])&0xFF);
      }
      }
    
      
  
        lcd.clear();
       for(adresaEEPROM=0;adresaEEPROM<sizeof(kaladc);adresaEEPROM++)
      {
        EEdata = EEPROM.read(adresaEEPROM++);
        //lcd.print(EEdata,HEX);
        //lcd.print(" ");
        EEdata1 = EEPROM.read(adresaEEPROM);
        //lcd.print(EEdata1,HEX);
        //lcd.print(adresaEEPROM);
        //EEint=EEdata<<8|EEdata1;
        EEint=EEdata<<8|EEdata1;
        //lcd.print(sizeof(kaladc));
        lcd.print(EEint);
       Serial.print(EEint);
       Serial.print(" ");
        lcd.print(" ");
        delay(500);
      }
      
    }    
  }  
  else {
    Serial.println("error opening file.txt");
  }     
        delay(1000);
      }

      lcd.clear();
      digitalWrite(LEDTL7, HIGH);
    }
  pomLCD=0; 
  lcd.clear();
  }  
  
  
  command = Serial.read();
  if (command == 84 || command == 116)                //If command = "T or t" 
  { 
    int reading3V3 = analogRead(voltage3);    
    Serial.print("3V3: ");
    Serial.print(((reading3V3*2.5/1024)/712)*1000);
    Serial.println(" V");
    int reading12V = analogRead(Vcc13);                                        //12V reading
    Serial.print("Ucc: ");
    Serial.print(((reading12V*2.5/1024)/17)*100);
    Serial.println("V");
    readingTERM = analogRead(TERM);
    Serial.print("temp:");
    Serial.print(140-(0.1774*readingTERM));
    Serial.println(" st Celsia");
  }
  if (command == 0x50 || command == 0x70)                 //If command = "P or p" display
  {
    if(digitalRead(BackLight) == 1)
    {
      Serial.println("BackLight: OFF");
      PORTJ=(0<<PJ3);
    }
     else
     {
      Serial.println("BackLight: ON");
      PORTJ=(1<<PJ3);
     }
     
  }
   if (command == 0x55 || command == 0x75)                 //If command = "U or u" frequency UP
  {
      //b = (byte) Serial.read();
      //  b = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
     FREK_OFFSET=0;
     frekChan[selChan]++;
    // Serial.println(frekChan[selChan]);
     if (frekChan[selChan]>=11)
    {
      frekChan[selChan]=0;
    }
    switch (selChan)
      {case 0:
        Serial.print(kalfreq[sondadet1-1][frekChan[0]]);
        Serial.println("MHz");
         break;
     
      case 1:
        Serial.print(kalfreq[sondadet2-1][frekChan[1]]);
        Serial.println("MHz");
       break;
       
       case 2:
         Serial.print(kalfreq[sondadet3-1][frekChan[2]]);
         Serial.println("MHz");
       break;
       
        case 3:
         Serial.print(kalfreq[sondadet4-1][frekChan[3]]);
         Serial.println("MHz");
       break;}
  }
   if (command == 68 || command == 100)                 //If command = "D or d" frequency DOWN
  {
     FREK_OFFSET=0;
     frekChan[selChan]--;
     if (frekChan[selChan]>=0xFF)
    {
      frekChan[selChan]=10;
    }
     //Serial.println(frekChan[selChan]);
     switch (selChan)
      {case 0:
        Serial.print(kalfreq[sondadet1-1][frekChan[0]]);
        Serial.println("MHz");
         break;
     
      case 1:
        Serial.print(kalfreq[sondadet2-1][frekChan[1]]);
        Serial.println("MHz");
       break;
       
       case 2:
         Serial.print(kalfreq[sondadet3-1][frekChan[2]]);
         Serial.println("MHz");
       break;
       
        case 3:
         Serial.print(kalfreq[sondadet4-1][frekChan[3]]);
         Serial.println("MHz");
       break;}
    // Serial.print(kalfreq[1][frekChan[0]]);
     //Serial.print(kalfreq[sondadet2-1][frekChan[1]]);
    // Serial.println(" MHz");
  }
  
  
   if (command == 0x4D || command == 0x6D)                 //If command = "M or m" panel meter
  {
    if(pomPWM==0)
    {
      Serial.println("PWM: ON");
      pomPWM=1;
      
     
    }
    else
    {
      Serial.println("PWM: OFF");
      pomPWM=0;
    }    
      
  }
  
   if (command == 0x4F || command == 0x6F)                 //If command = "O or o" Offset setting
  {
    // b = (byte) Serial.read();
     FREK_OFFSET=1;
     b = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
     offset[selChan]=b;
     Serial.print("OFFSET: ");
     Serial.print(b);
     Serial.println("dB");
  }
   if (command == 0x41 || command == 0x61)                 //If command = "A or a" Offset UP
  {
    FREK_OFFSET=1;
   offset[selChan]+=0.1;
   Serial.print("+offset: ");
   Serial.print(offset[selChan]);
   Serial.println("dB");
  
  }
   if (command == 0x42 || command == 0x62)                 //If command = "B or d" Offset DOWN
  {
    FREK_OFFSET=1;
   offset[selChan]-=0.1;
   if (offset[selChan]<0)
   {
     offset[selChan]=0;
   }
   Serial.print("-offset: ");
   Serial.print(offset[selChan]);
   Serial.println("dB");
   
  }
  
   if (command == 0x43 || command == 0x63)                 //If command = "C or c" Set channal
  {  
      
      c = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
      
      if (c>3)
      {
        c=3;
      }
       selChan=c;
       Serial.print("*********Vybran kanal c: ");
       Serial.print(c+1);
       Serial.println(" *********");
      
            
      /* if (selChan==0)
       {
         Serial.println(kalfreq[sondadet1-1][frekChan[0]]);
       }*/
  }
   
  command=0;

int reading12V = analogRead(Vcc13);
if(reading12V < 820 & pomVcc == 0)
  { 

    lcd.clear();
    lcd.setCursor(10,1);
    lcd.print("Battery LOW ");
    Serial.println("Battery LOW");
    lcd.print(((reading12V*2.5/1024)/17)*100);
    lcd.print("V ");
    lcd.print(reading12V);
    PORTJ=(0<<PJ3);
    delay(1000);
    PORTJ=(1<<PJ3);
    delay(1000);
    PORTJ=(0<<PJ3);
    delay(1000);
    PORTJ=(1<<PJ3);
    delay(4000);
    PORTJ=(0<<PJ3);
    lcd.clear();
    pomVcc=1;
   
  }

  if (pomPWM ==1)                                                // PWM tlacitko zapnuto
  { switch (selChan)
    {case 0:
     PWMvalue = map(prum1, 132, 1023, 18, 123);
     break;
     
     case 1:
     PWMvalue = map(prum2, 132, 1023, 18, 123);
     break;
     
     case 2:
     PWMvalue = map(prum3, 132, 1023, 18, 123);
     break;
     
     case 3:
     PWMvalue = map(prum4, 132, 1023, 18, 123);
     break;}
    analogWrite(PWMOUT, PWMvalue);
    digitalWrite(LEDTL3, LOW);
  }
  else
  { 
    analogWrite(PWMOUT,18);
    digitalWrite(LEDTL3, HIGH);
    
  }
if (pomPSW == 1)
{
  if (pomVypis==0)
  {
       lcd.setCursor(15,0);
       lcd.print("Mereni PSV");
       Serial.println("-----Mereni PSV-----");
       lcd.setCursor(5,1);
       lcd.print("Merim z kanalu 1 a kanalu 2");
       pomVypis=1;
       delay(3000);
       lcd.clear();
  }else
       if (det1 == 1 && det2 == 1 && pomVypis == 1 && pomVypPSQV==0)
       {
         lcd.clear();
        lcd.setCursor(0,1);
        lcd.print("P1:");   lcd.print(P1);
        lcd.setCursor(10,1);
        lcd.print("P2:");   lcd.print(P2);
        lcd.setCursor(5,2);
        rho=sqrt(P1/P2);
        lcd.print("rho: ");
        lcd.print(P1);
        lcd.setCursor(4,3);
        lcd.print("PSV: ");
        PSV=(1+rho) / (1-rho);
        lcd.print(PSV);
        lcd.print(" :1");
        pomVypPSQV=0;
        delay(1500);
        
        
       }
       else
       {
       lcd.clear();
       lcd.print("    Kanaly 1 a 2 nejsou pripojeny");
       lcd.setCursor(8,2);
       lcd.print("Pripoj kanaly 1 a 2");
       delay(2000);
       lcd.clear();
       pomPSW=0;
       }
}


if ((pomLCD==0) && (det1 == LOW) && (det2 == LOW) && (det3 == LOW) && (det4 == LOW))                          //if is no sond connected
  {
    lcd.clear();
    lcd.setCursor(8,1);
    lcd.print("No power sensor connected!");
    lcd.setCursor(5,2);
    lcd.print("Please connect any power sensor.");
    a=0;
    d=0;
    f=0;
    
    pomLCD=1;
    

  }



}
