/*******************************************************************************
 *  debounce.c - Push button debounce routines.
 *
 *  Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ 
 *  ALL RIGHTS RESERVED 
 * 
*/

#include <inttypes.h>
#include "emeter-toolkit.h"

/* A routine to debounce a push button switch */
int debounce(uint8_t *deb, uint8_t key_up)
{
    if (*deb <= 127)
    {
        /* Waiting for key to go down */
        if (key_up)
        {
            *deb = 0;
        }
        else
        {
            if (++*deb >= BUTTON_PERSISTENCE_CHECK)
            {
                *deb = 255;
                return  DEBOUNCE_JUST_HIT;
            }
        }
        return  DEBOUNCE_RELEASED;
    }
    else
    {
        /* Waiting for key to go up */
        if (key_up)
        {
            if (--*deb <= (255 - BUTTON_PERSISTENCE_CHECK))
            {
                *deb = 0;
                return  DEBOUNCE_JUST_RELEASED;
            }
        }
        else
        {
            *deb = 255;
        }
        return  DEBOUNCE_HIT;
    }
}
