/***********************************************
 * 電球ウインカー風 
 ************************************************/
#include <xc.h>
#include <stdint.h>
#include "mcr.h"
#include "adc.h"
#include "io.h"
#include "incr-exp.h"

/* 
 * 指数関数（CR充電曲線の形）で輝度が変化
 */

/* 時定数 0..255 */
#define TCONST_ON    6
#define TCONST_OFF   4

/* 有限状態機械 */
enum fsm_state_e {
  STATE_Q0 = 0, /* 停止期間 */
  STATE_Q1,     /* 点灯期間 */
  STATE_Q2,     /* 消灯期間 */
};

void Light(void)
{
  /* 状態 */
  enum fsm_state_e fsm_state = STATE_Q0;
  /* 現在輝度 */
  uint16_t intensity_current = 0;
  incr_exp_init(intensity_current);
  /* 点滅時間計測用 */
  uint16_t tmr = 0;
  /* 主ループ */
  for (;;) {
    CLRWDT();
    __delay_ms(10); /* 1サイクル 10 [mSec] */
    /* On/Offスイッチ*/
    int8_t sw_on = SW_ON();
    /* 点滅周期をパラメータボリュームから読む */
    uint16_t blink_cycle = 5 + (ADC_Read(ADC_CH_PARAM) >> 2);
    /* 有限状態機械 */
    switch (fsm_state) {
    case STATE_Q0: /* 停止期間 */
      if (sw_on) {
        fsm_state = STATE_Q1;
        tmr = blink_cycle;
        incr_exp_init(intensity_current);
      } else {
        intensity_current
          = incr_exp_next(TCONST_ON, 0);
      }
      break;
    case STATE_Q1: /* 点灯期間 */
      if (sw_on) {
        if (tmr == 0) {
          fsm_state = STATE_Q2;
          tmr = blink_cycle;
          incr_exp_init(intensity_current);
        } else {
          tmr = tmr - 1;
        }
      } else {
        incr_exp_init(intensity_current);
        fsm_state = STATE_Q0;
      }
      intensity_current
        = incr_exp_next(TCONST_ON, INTENSITY_MAX);
      break;
    case STATE_Q2: /* 消灯期間 */
      if (sw_on) {
        if (tmr == 0) {
          fsm_state = STATE_Q1;
          tmr = blink_cycle;
          incr_exp_init(intensity_current);
        } else {
          tmr = tmr - 1;
        }
      } else {
        fsm_state = STATE_Q0;
      }
      intensity_current
        = incr_exp_next(TCONST_OFF, 0);
      break;
    }
    /* 輝度出力 */
    LED_INTENSITY(intensity_current);
  }
}
