/*-------------------------------------------------------
 * ロータリーエンコーダ
 *-------------------------------------------------------*/
#include <xc.h>
#include <stdint.h>
#include "io.h"
#include "rotenc.h"

int8_t rotenc_scan(void)
{
  /* 回転方向: +1 (正) / 0 (無) / -1 (逆) */
  int8_t value = 0;
  /* 現在入力値 */
  int8_t curr_a = SW_ROTENC_A(); /* 0:ON, 1: OFF */
  int8_t curr_b = SW_ROTENC_B(); /* 0:ON, 1: OFF */
  /* チャタリング除去処理 */
  uint8_t stab_done = 0;
  static uint8_t chat_stab_t = 0;
  static int8_t  chat_prev_a = 0; 
  static int8_t  chat_prev_b = 0; 
  if ((chat_prev_a == curr_a) &&
      (chat_prev_b == curr_b)) {
    chat_stab_t++;
    if (chat_stab_t == ROTENC_STAB_TIME) { /* 収束 */
      stab_done = 1; /* チャタリング除去完了 */
      chat_stab_t = 0;
    }
  } else { /* 進行中 */
    chat_stab_t = 0; /* チャタリング除去未完了 */
    chat_prev_a = curr_a;
    chat_prev_b = curr_b;
  }
  /* 回転方向検出 */
  static int8_t prev_a = 0; 
  static int8_t prev_b = 0; 
  if ((stab_done == 1) &&
      ((prev_a != curr_a) || (prev_b != curr_b))) {
    /* チャタリング除去完了 かつ ロータリエンコーダ出力変化あり */
    if ((prev_b != 0) && (curr_b == 0) && /* B: OFF -> ON */
        (curr_a == 0)) { /* A: ON */
      /* 正方向の回転 */
      value = +1;
    }
    if ((prev_a != 0) && (curr_a == 0) && /* A: OFF -> ON */
        (curr_b == 0)) { /* B: ON */
      /* 逆方向の回転 */
      value = -1;
    }
    prev_a = curr_a;
    prev_b = curr_b;
  }
  return value;
}
