#include <stdio.h>
#include <stdlib.h>
#include "setup.h"
#include <xc.h>

//void hlidej (void);
#define COUNT 5//@ 8MHz = 125uS.
//#define ETIME COUNT*2.5 //time in uS
#define DELAY for(i=0;i<COUNT;i++)
//#define ADSCALE 1023 //for unsigned conversion 10 sig bits
//#define ADREF 3.1 //Vdd connected to A/D Vr+
//#define RCAL .027 //R value is 4200000 (4.2M)
//scaled so that result is in
//1/100th of uA

#define KON 300
#define DELAYL for(m=0;m<800;m++)
#define DELAYL1 for(l=0;l<200000;l++)
#define DELAYL2 for(l=0;l<80000;l++)
#define DELAYLA for(j=0;j<110000;j++)
#define POCKEJ for(k=0;k<300;k++)
#define OPENSW 1000 //Un-pressed switch value

#define HYST 10 //amount to change
#define OPAK 15 //amount to change
#define PRESSED 1
#define UNPRESSED 0
unsigned char EN=0,pp=0;


// PIC18F24J11 Configuration Bit Settings

// 'C' source line config statements

// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.

// CONFIG1L
#pragma config WDTEN = ON      // Watchdog Timer (Disabled - Controlled by SWDTEN bit)
#pragma config STVREN = ON      // Stack Overflow/Underflow Reset (Enabled)
#pragma config XINST = OFF      // Extended Instruction Set (Disabled)

// CONFIG1H
#pragma config CP0 = OFF        // Code Protect (Program memory is not code-protected)

// CONFIG2L
#pragma config OSC = INTOSCPLL  // Oscillator (INTOSCPLL)
#pragma config T1DIG = ON       // T1OSCEN Enforcement (Secondary Oscillator clock source may be selected)
#pragma config LPT1OSC = OFF    // Low-Power Timer1 Oscillator (High-power operation)
#pragma config FCMEN = ON       // Fail-Safe Clock Monitor (Enabled)
#pragma config IESO = ON        // Internal External Oscillator Switch Over Mode (Enabled)

// CONFIG2H
#pragma config WDTPS = 512//32768    // Watchdog Postscaler (1:32768)

// CONFIG3L
#pragma config DSWDTOSC = INTOSCREF// DSWDT Clock Select (DSWDT uses INTRC)
#pragma config RTCOSC = T1OSCREF// RTCC Clock Select (RTCC uses T1OSC/T1CKI)
#pragma config DSBOREN = ON     // Deep Sleep BOR (Enabled)
#pragma config DSWDTEN = ON     // Deep Sleep Watchdog Timer (Enabled)
#pragma config DSWDTPS = G2     // Deep Sleep Watchdog Postscaler (1:2,147,483,648 (25.7 days))

// CONFIG3H
#pragma config IOL1WAY = ON     // IOLOCK One-Way Set Enable bit (The IOLOCK bit (PPSCON<0>) can be set once)
#pragma config MSSP7B_EN = MSK7 // MSSP address masking (7 Bit address masking mode)

// CONFIG4L
#pragma config WPFP = PAGE_15   // Write/Erase Protect Page Start/End Location (Write Protect Program Flash Page 15)
#pragma config WPEND = PAGE_WPFP// Write/Erase Protect Region Select (valid when WPDIS = 0) (Page WPFP<5:0> through Configuration Words erase/write protected)
#pragma config WPCFG = OFF      // Write/Erase Protect Configuration Region (Configuration Words page not erase/write-protected)

// CONFIG4H
#pragma config WPDIS = OFF      // Write Protect Disable bit (WPFP<5:0>/WPEND region ignored)

//void interrupt low_priority tmr0_int (void){
// if (INTCONbits.TMR0IF) {
// INTCONbits.TMR0IF = 0;
// EN=0;
// pp++;
// }
//}

//long tick_count;
//void interrupt tc_int(void){
//
////C Language Features Interrupt Handling in C
//++tick_count;
//}
////A low-priority interrupt function may be defined as in the following example.
//void interrupt low_priority tc_clr(void){
//tick_count = 0;
//}
unsigned int timer_on_2=0;
unsigned char tlacitka[10];

int main (void) {

WDTCONbits.SWDTEN = 1;    
unsigned int Vread=0,Vavg,VTot,Ttot,VreasFil[10]; //storage for reading
unsigned int switchState;
unsigned int timer_on=0;
int Sdel,TRIP[13]={250, 250, 445, 380, 314, 250, 250, 250, 325, 310, 260,325,295}; //Difference between pressed
//                  - ,  - , <- , -> , OK ,  - ,  - ,  - ,  - ,  - , ? , ON , ^
int i,a,qq;
unsigned long j,l;
int m,k,Lpoz,Ppoz,del1,del1l,del1h,del2,del2l,del2h,pom;    
unsigned char TX,Shif_EN = 0,poc=1;    
unsigned char EN=0;
char POSUV=0, POZ,POZbuf=0;

unsigned int kond1,kond2,kond3,kond4,kond5,kond6,Stot,amb1,amb2,amb3,amb4,amb5,amb6;
setup();
        
    
while(1){
ClrWdt();

CTMUCONHbits.CTMUEN = 1; //Enable the CTMU
CTMUCONLbits.EDG1STAT = 0; // Set Edge status bits to zero
CTMUCONLbits.EDG2STAT = 0;
Ttot=0;

for(a=0;a<13;a++)
{
 //ClrWdt();
    if  (a==5 || a==6 || a==7 )
    continue;

    ADCON0bits.CHS=a;
    VTot=0;
//    Stot=0;
    for(qq=0;qq<50;qq++)
        {
        CTMUCONHbits.IDISSEN = 1; //drain charge on the circuit
        DELAY; //wait 125us
        CTMUCONHbits.IDISSEN = 0; //end drain of circuit
        CTMUCONLbits.EDG1STAT = 1; //Begin charging the circuit
        //using CTMU current source
        DELAY; //wait for 125us
        CTMUCONLbits.EDG1STAT = 0; //Stop charging circuit
        PIR1bits.ADIF = 0; //make sure A/D Int not set
        ADCON0bits.GO=1; //and begin A/D conv.

        while(!PIR1bits.ADIF); //Wait for A/D convert complete
        Vread = ADRES; //Get the value from the A/D
        VTot += Vread; //Add the reading to the total
        }

   Vavg = (VTot/50); //Average of 10 readings
   Vavg=1024-Vavg-TRIP[a]+100;

   if (Vavg>800)
       Vavg=0;


       //filter low-pass
//Y[i]=Y[i-1]+a*(X[i]-Y[i-1]) ; a=0,3  *307/1024
//     VreasFil[a] = (VreasFil[a] + ((3*(Vread[a]-VreasFil[a]))>>3));

    if (a==8)
    {del2 = Vavg;
        if (del2<0)
           del2=0;
    }

    if (a==9)
    {del1 = Vavg;
         if (del1<0)
           del1=0;
    
    Lpoz = ((del1*100)/(del1+del2));
    Ppoz = (((1-del2)*100)/(del1+del2));
    POZ = 50+((Lpoz+Ppoz)/2);
    }

      if (a==3)
          amb1=Vavg;

       if (a==2)
          amb2=Vavg;

       if (a==4)
          amb3=Vavg;

       if (a==11)
          amb4=Vavg;
   
       if (a==10)
          amb5=Vavg;

       if (a==12)
          amb6=Vavg;

        if (a==3)
        kond1=Vavg;

        if (a==2)
        kond2=Vavg;

        if (a==11)    //4,11,3,2,12,10
        kond3=Vavg;

        if (a==4)
        kond4=Vavg;

        if (a==10)    
        kond5=Vavg;

        if (a==12)
        kond6=Vavg;

if(Vavg > 35)
    {
       switch(a){
        case 2:
          tlacitka[0] = 1;
          timer_on=0;
          break;

        case 4:
          tlacitka[5] = 1;
          timer_on=0;
          break;

        case 3:
          tlacitka[2] = 1;
          timer_on=0;
          break;

        case 12:
         tlacitka[3] = 1;
         timer_on=0;
         break;

        case 11:
          if (timer_on == 30)   //ur?uje ?as na zapnutí/vypnutí
          {
              tlacitka[6] = 1;
              timer_on=0;
          }
          ++timer_on;
          break;

        case 10:
          tlacitka[4] = 1;
        }
       
    }

else if(Vavg < 30)
    {
        switch(a){
        case 2:
        tlacitka[0] = 0;
        break;
        case 4:
        tlacitka[5] = 0;
        break;
        case 3:
        tlacitka[2] = 0;
        break;
        case 12:
        tlacitka[3] = 0;
        break;
        case 11:
        tlacitka[6] = 0;
        timer_on=0;
        break;
        case 10:
        tlacitka[4] = 0;
        }
      
    }
      PIR1bits.ADIF = 0; //make sure A/D Int not set
      ADCON0bits.CHS = 0b1111;
      ADCON0bits.GO=1; //and begin A/D conv.
      while(!PIR1bits.ADIF); //Wait for A/D convert complete
      ADCON0bits.GO=1; //and begin A/D conv.
      while(!PIR1bits.ADIF); //Wait for A/D convert complete
  }


 if ((amb4>10 && amb3>10) && amb4<120 && amb3<120)
  { tlacitka[7] = 1;
    tlacitka[5] = 0;
    tlacitka[6] = 0;
  }
 else
     tlacitka[7] = 0;

 if ((amb1>10 && amb2>10)&& amb1<120 && amb2<120 )
  { tlacitka[8] = 1;
    tlacitka[0] = 0;
    tlacitka[2] = 0;
  }
 else
     tlacitka[8] = 0;

 if ((amb5>10 && amb6>10)&& amb5<120 && amb6<120 )
  { tlacitka[9] = 1;
    tlacitka[4] = 0;
    tlacitka[3] = 0;
  }
 else
     tlacitka[9] = 0;

if (tlacitka[0] + tlacitka[2] + tlacitka[3] + tlacitka[4] + tlacitka[1] - 1)
  { tlacitka[1] = 0;
    tlacitka[0] = 0;
    tlacitka[2] = 0;
    tlacitka[3] = 0;
    tlacitka[4] = 0;
   }


    if (tlacitka[6])
        {
          if  (LATCbits.LC6==1)
          {
            SSP1BUF = 0b11111111; //sleep
            POCKEJ;
            POCKEJ;
            LATCbits.LC6=0;
            //snizit spotrebu
            //hlidej();            
//            if(RCONbits.TO == 0)
//             LATCbits.LC6=1;   //zapne napájení
             //hlidej();
          }
          else
            LATCbits.LC6=1;
        }
    //ClrWdt();

    if (tlacitka[0] || tlacitka[2] || tlacitka[3] || tlacitka[4] || tlacitka[5]|| tlacitka[6] || tlacitka[7] || tlacitka[8] || tlacitka[9])
    {
    SSP1BUF = 0b11100000;
    POCKEJ;

    if  (tlacitka[5])
    SSP1BUF = 0b00000001;
    else if  (tlacitka[0])
    SSP1BUF = 0b00000010;
    else if  (tlacitka[2])
    SSP1BUF = 0b00000100;
    else if  (tlacitka[3])
    SSP1BUF = 0b00001000;
    else if  (tlacitka[4])
    SSP1BUF = 0b00010000;
    else if  (tlacitka[6])
    SSP1BUF = 0b00000000;
    else if  (tlacitka[7])
    SSP1BUF = 0b00100000;
    else if  (tlacitka[8])
    SSP1BUF = 0b01000000;
    else if  (tlacitka[9])
    SSP1BUF = 0b10000000;
    DELAYL1;

   }
    
  //Shift  
//
//        if (((del2+del1)>30))
//    {
//        TMR0=0;
//        poc=1;
//        Sdel = POZ-POZbuf;

//
////        if ((Sdel>12 && EN==1) || (Sdel>12 && Shif_EN==1))
////        {
////        POSUV= 0b00000100;
////        Shif_EN = 1;
////        }
////        else if((Sdel<(-12) && EN==1)|| (Sdel<(-12) && Shif_EN==2))
////        {
////        POSUV= 0b00000010;
////        Shif_EN = 2;
////        }
////        else if((POZ>85))// && Shif_EN==1)
////        POSUV= 0b00000100;
////        else if((POZ<15))//&& Shif_EN==2)
////        POSUV= 0b00000010;
//////        else if(POZ>40 && POZ<60)
//////        POSUV= 0b00000001;
////        else
////        {
////        POSUV=0;
////        Shif_EN = 0;
////        }
//
//        EN=1;
//        POZbuf  = POZ;
//  //ClrWdt();
//        POCKEJ;
//        SSP1BUF = 0b00011100;
///////////////////////////////////////////
//        POCKEJ;
//        del1l = kond1 & 0x00FF;
//        SSP1BUF = del1l;
//
//        POCKEJ;
//        del1l = kond2 & 0x00FF;
//        SSP1BUF = del1l;
//
//        POCKEJ;
//        del1l = kond3 & 0x00FF;
//        SSP1BUF = del1l;
//
//        POCKEJ;
//        del1l = kond4 & 0x00FF;
//        SSP1BUF = del1l;
//
//        POCKEJ;
//        del1l = kond5 & 0x00FF;
//        SSP1BUF = del1l;
//
//         POCKEJ;
//        del1l = kond6 & 0x00FF;
//        SSP1BUF = del1l;
//  //ClrWdt();
////////////////////////////////////////
//        POCKEJ;
//        SSP1BUF = POZ;
//
//        POCKEJ;
//        del1l = kond3 & 0x00FF;
//        SSP1BUF = del1l;
//
//        POCKEJ;
//        kond3 >>=8;
//        del1h = kond3 & 0x00FF;
//        SSP1BUF = del1h;
//
//        POCKEJ;
//        del2l = kond4 & 0x00FF;
//        SSP1BUF = del2l;
//
//        POCKEJ;
//        kond4 >>=8;
//        del2h = kond4 & 0x00FF;
//        SSP1BUF = del2h;
//
//        POCKEJ;
//        SSP1BUF = Lpoz;
//
//        POCKEJ;
//        SSP1BUF = Ppoz;
//
//        POCKEJ;
//        SSP1BUF =  POSUV;
//
//        POCKEJ;
//        SSP1BUF =  (char) Sdel;
//
//
//        // zpo?d?ní
//        if  (POSUV!=0)
//        DELAYL2;
//
//      }
//        else
//        {
//        Shif_EN = 0;
//        EN=0;
//        }

    }
}

//void hlidej (void)
//{
////ClrWdt();
//
//unsigned int Vread=0,Vavg,VTot,Ttot; //storage for reading
//int Sdel,TRIP= 525; //Difference between pressed
//int i,a=11,qq,k;
//unsigned long l;
//    
//    timer_on_2=0;
//    
//    ADCON1bits.ADFM=1; // Result format 1= Right justified
//    ADCON1bits.ADCAL=0; // Normal A/D conversion operation
//    ADCON1bits.ACQT=1; // Acquisition time 7 = 20TAD 2 = 4TAD 1=2TAD
//    ADCON1bits.ADCS=0; // Clock conversion bits 6= FOSC/64 2=FOSC/32
//    ANCON1bits.VBGEN=1; // Turn on the Bandgap
//    while(1)
//   {
//    CTMUICON = 0b10000110;
//    CTMUCONLbits.EDG1STAT = 0; // Set Edge status bits to zero
//    CTMUCONLbits.EDG2STAT = 0;
//
//        
//    ADCON0bits.CHS=a;
//    VTot=0;
//    for(qq=0;qq<2;qq++)
//        {
//        CTMUCONHbits.IDISSEN = 1; //drain charge on the circuit
//        DELAY; //wait 125us
//        CTMUCONHbits.IDISSEN = 0; //end drain of circuit
//        CTMUCONLbits.EDG1STAT = 1; //Begin charging the circuit
//        //using CTMU current source
//        DELAY; //wait for 125us
//        CTMUCONLbits.EDG1STAT = 0; //Stop charging circuit
//        PIR1bits.ADIF = 0; //make sure A/D Int not set
//        ADCON0bits.GO=1; //and begin A/D conv.
//
//        while(!PIR1bits.ADIF); //Wait for A/D convert complete
//        Vread = ADRES; //Get the value from the A/D
//        VTot += Vread; //Add the reading to the total
//        }
//
//   Vavg = (VTot/2); //Average of 10 readings
//   Vavg=1024-Vavg-TRIP+100;
//
//   if (Vavg>800)
//       Vavg=0;
//   
//       if(Vavg > 35)
//       {
//           if (timer_on_2 == 5)
//           {
//               timer_on_2=0;
//
//               LATCbits.LC6=1;   //zapne napájení
//              
//              return ;
//           }
//       ++timer_on_2;
//       }
//       else
//        timer_on_2=0;
//   
//   
//      PIR1bits.ADIF = 0; //make sure A/D Int not set
//      ADCON0bits.CHS = 0b1111;
//      ADCON0bits.GO=1; //and begin A/D conv.
//      while(!PIR1bits.ADIF); //Wait for A/D convert complete
//      ADCON0bits.GO=1; //and begin A/D conv.
//      while(!PIR1bits.ADIF); //Wait for A/D convert complete
//      
//    OSCCONbits.IDLEN = 0;
//    Sleep();
//   }  
//}


// #asm   // like this...
//   movlw    0x00
//   movwf    TRISC
//#endasm
//   asm("bsf PORTC,3");


//while(1){
//    if (PORTCbits.RC0 == 1)
//        PORTCbits.RC1 = 1;
//    else
//        PORTCbits.RC1 = 0;
//} 
