/***********************************************************
 * パワーパック(低速ブースト・加減速機能PWM型・RS-232C制御) 
 *   / PIC16F18857
 * by Hirotsugu Kakugawa
 ***********************************************************/
#include <xc.h>
#include <stdint.h>
#include "mcr.h"
#include "mcr-motor.h"
#include "io.h"
#include "ir-frame.h"
#include "keysym.h"
#include "rc.h"
#include "cmd.h"
#include "adc.h"
#include "if.h"
#include "if-toq.h"
#include "pp.h"
#include "pp-const.h"
#include "pp-sb.h"

enum ctrmode_e fsm_ctrmode = CTRMODE_REMOTE;
extern void auto_select(void);

/*------------------------------------------------------- 
 * MAIN
 *-------------------------------------------------------*/
void main(void) 
{
  /* システム初期化 */
  System_Init();
  /* ウオッチドッグタイマ: 256 [mSec] */
  WDTCON0bits.WDTPS = 0x08; /* 0b01000 */
  CLRWDT();
  /* モータ出力初期化 */
  MOTOR_DIR_NONE();
  MOTOR_PWM_START();
  /* LED */
  LED_INDICATOR_OFF();  /* 状態インジケータLED */
  LED_STOPPED_OFF();    /* 停車中表示LED */
  __delay_ms(100);
  CLRWDT();
  /* ポイント切替動作キュー初期化 */
  if_toq_init();
  /* 低速ブースト初期化 */ 
  pp_sb_init();
  /* 割り込み許可 */ 
  GIE  = 1;
  PEIE = 1;
  /* 制御モード: リモコン/手動 */
  if (SW_CTRMODE_REMOTE()) {
    fsm_ctrmode = CTRMODE_REMOTE;
    auto_select();      /* リモコン自動選択 */
    LED_IR_MON_ON();    /* リモコン受信モニタ点灯 */
  } else {
    fsm_ctrmode = CTRMODE_MANUAL;
    pp_home_position(); /* ラッシュ防止機能 */
  }
  /* 主ループ */
  for (;;) {
    CLRWDT();
    /* フレーム受信フラグをクリア */
    ir_rcv_flag = 0;
    /* パワーパック走行制御 */
    pp_control();
  }
}
