/********************************************/
/*Debouncing for the touch screen           */
/*PIC32MX795F512L-80I/PF                    */
/********************************************/
#include <xc.h>
#include "Debounce.h"
#include "Touch.h"
#include "Delay.h"

void Debounce(void)
{
    //get three touch coordinates separated by a delay and compare
    //if more than 10 difference retry
    int dval = 60000;
    int tol = 10;
    //get the touch values
    //xtouch[0] is the saved value of data_x
    PORTAbits.RA6 = 0;
    xtouch[0] = data_x;
    ytouch[0] = data_y;
    
    Delay(dval);
    
    xtouch[1] = data_x;
    ytouch[1] = data_y;
    
    Delay(dval);
    
    xtouch[2] = data_x;
    ytouch[2] = data_y;
    PORTAbits.RA6 = 1;
    //x-axis
    if(xtouch[0] >= xtouch[1])
    {
       xtouch[1] = xtouch[0] - xtouch[1];
    }
    else
    {
       xtouch[1] = xtouch[1] - xtouch[0];
    }
    
    if(xtouch[0] >= xtouch[2])
    {
       xtouch[2] = xtouch[0] - xtouch[2];
    }
    else
    {
       xtouch[2] = xtouch[2] - xtouch[0];
    }
    
    //if xtouch[1] and xtouch[2] are both below 10
    //then average and compare with xtouch[0]
    if((xtouch[1] > tol) || (xtouch[2] > tol))
    {
        debounce = 0;
        return;
    }
    
    //y-axis
    //ytouch[0] is the saved value of data_y
    if(ytouch[0] >= ytouch[1])
    {
       ytouch[1] = ytouch[0] - ytouch[1];
    }
    else
    {
       ytouch[1] = ytouch[1] - ytouch[0];
    }
    
    if(ytouch[0] >= ytouch[2])
    {
       ytouch[2] = ytouch[0] - ytouch[2];
    }
    else
    {
       ytouch[2] = ytouch[2] - ytouch[0];
    }
    
    //if xtouch[1] and xtouch[2] are both below 10
    //then average and compare with xtouch[0]
    if((ytouch[1] > tol) || (ytouch[2] > tol))
    {
        debounce = 0;
        return;
    }
    
    //xtouch[0] contains the data_x value
    //ytouch[0] contains the data_y value
    
    debounce = 1;

    return;
}

