/*------------------------------------------------------- 
 * SW状態読み取り
 *   タイマ割り込みで定期的に読み取り、チャタリング除去する
 *-------------------------------------------------------*/
#include <xc.h>
#include <stdint.h>
#include "mcr.h"
#include "io.h"
#include "sw.h"

#define SW_CNT_THREASHOULD  20
volatile int8_t  sw_state_play_val = 0;
volatile uint8_t sw_state_play_cnt = 0;

void sw_reader_init(void)
{
  sw_state_play_val = SW_PLAY();
  sw_state_play_cnt = SW_CNT_THREASHOULD;
}

int8_t sw_reader_get_play(void)
{
  return sw_state_play_val;
}

void sw_reader_isr(void)
{
  switch (sw_state_play_val) {
  default:  
  case 0: /* SW OFF */
    if (!SW_PLAY()) {
      sw_state_play_cnt = SW_CNT_THREASHOULD;
    } else {
      if (sw_state_play_cnt != 0) {
        sw_state_play_cnt--;
      } else {
        sw_state_play_val = 1;
      }
    }
  break;
  case 1: /* SW ON */
    if (SW_PLAY()) {
      sw_state_play_cnt = SW_CNT_THREASHOULD;
    } else {
      if (sw_state_play_cnt != 0) {
        sw_state_play_cnt--;
      } else {
        sw_state_play_val = 0;
      }
    }
    break;
  }
}
