
/* MalZeit 08/2014 */


#include "taster_ports.h"

#include <stddef.h>

#include <avr/io.h>

#ifndef DDR_OFFSET
  #define DDR_OFFSET(X) (*(&X-1))
#endif
#ifndef PIN_OFFSET
  #define PIN_OFFSET(X) (*(&X-2))
#endif


#define TASTER1          (PORTB)
#define TASTER1_PIN      (1<<PB0)
#define TASTER2          (PORTB)
#define TASTER2_PIN      (1<<PB1)

#define TASTER_PORTS_ENTPRELLEN_MS 50


static void (*gpTasterEreignis) (void) = NULL; // INIT and ISR


void TasterPortsInit(void);
void TasterPortsRegistriereEreignisCb(void (*pTasterEreignis) (void));
void TasterPortsTimerCb(void);

/**
 * 
 * TODO Vorläufige Zwei-Taster-Lösung
 */
void TasterPortsInit(void)
{

  DDR_OFFSET(TASTER1) &= ~TASTER1_PIN; // input
  DDR_OFFSET(TASTER2) &= ~TASTER2_PIN; // input
  
  TASTER1 |= TASTER1_PIN; // pull-up
  TASTER2 |= TASTER2_PIN; // pull-up
}  
  
/**
 *
 *
 *
 */  
void TasterPortsTimerCb(void)
{  
static uint8_t taster1EntrprellenMs = TASTER_PORTS_ENTPRELLEN_MS;
static uint8_t taster2EntrprellenMs = TASTER_PORTS_ENTPRELLEN_MS;

  // Flankenerkennung
  if(0 == (PIN_OFFSET(TASTER1) & TASTER1_PIN)) { // Taste gedrückt?
    // Wenn Entprellzeit überschritten, dann wurde Taste gerade gerückt
    if (taster1EntrprellenMs >= TASTER_PORTS_ENTPRELLEN_MS) { // unlock key pressed
      if (gpTasterEreignis != NULL) {
        gpTasterEreignis();
      }
    }
    taster1EntrprellenMs = 0; // Entprellzähler löschen solange Taste gedrückt
  }
  if(taster1EntrprellenMs < TASTER_PORTS_ENTPRELLEN_MS) {
    taster1EntrprellenMs += TASTER_PORTS_POLL_MS;
  }
  
  if(0 == (PIN_OFFSET(TASTER2) & TASTER2_PIN)) {
    if (taster2EntrprellenMs >= TASTER_PORTS_ENTPRELLEN_MS) { // unlock key pressed
      if (gpTasterEreignis != NULL) {
        gpTasterEreignis();
      }
    }
    taster2EntrprellenMs = 0;
  }
  if(taster2EntrprellenMs < TASTER_PORTS_ENTPRELLEN_MS) {
    taster2EntrprellenMs += TASTER_PORTS_POLL_MS;
  }
}

/**
 * 
 * INIT only
 * 
 */
void TasterPortsRegistriereEreignisCb(void (*pTasterEreignis) (void))
{
  gpTasterEreignis = pTasterEreignis;
}
  
// EOF