/* ----------------------------------------------------- 
 * 通過時間計測タイマ
 *-------------------------------------------------------*/
#include <xc.h>
#include <stdint.h>
#include "mcr.h"
#include "io.h"
#include "speed-timer.h"
#include "defs.h"

volatile static uint16_t speed_timer_overflows = 0;

/* 初期化 */
void speed_timer_init(void)
{
  TMR4_Init();
}

/* 計測開始 */
void speed_timer_start(void)
{
  speed_timer_overflows = 0;
  TMR4_Stop();
  TMR4_Write(0);
  TMR4_Start();
}

/* 計測終了: 計測結果を返す */
uint16_t speed_timer_end(void)
{
  /* [km/h] = 1000/3600[m/Sec] = 1/3.6[m/Sec] 
   *        = 100/3600 [cm/mSec] = 1/36 [cm/mSec] */
  TMR4_Stop();
  float t_ms 
    = SPEED_TMR_CYCLE 
    * ((float)speed_timer_overflows +
       (float)TMR4_Read() / 256.0);
  float speed_km_h = 0;
  if (t_ms == 0) {
    speed_km_h = 999;
  } else {
    speed_km_h = 36.0 * model_scale * sensor_dist_cm / t_ms;
  }
  return (uint16_t)(speed_km_h + 0.5);
}

/* 計測終了: 計測結果を返す */
uint16_t speed_timer_read(void)
{
  uint16_t t;
  int8_t ogie  = GIE;
  int8_t opeie = PEIE; 
  GIE   = 0;
  PEIE  = 0; 
  t = speed_timer_overflows;
  GIE   = ogie;
  PEIE  = opeie; 
  return t;
}
/* タイマオーバーフロー発生回数を勘定 */
void speed_timer_isr(void)
{
  speed_timer_overflows++;
}
