/******************************************************************************
*
* @file    fast_current.c
* @author  ECS, Falko Jahn
* @version V1.0.0
* @date    2022-01-16
* @brief       
*
******************************************************************************/

//	--- INCLUDES -----------------------------------------------------------------
#include "fast_current.h"
#include "main.h"
#include "sysdata.h"

//	--- EXTERNE VARIABLEN -------------------------------------------------------- 

//	--- LOKALE DEFINES - bitte hier dokumentieren --------------------------------
//#define FAST_CURRENT_FILTER  2



#define I_SENSE_GAIN    40.0


  #if (DEVICETYPE == 500)
    #define SHUNT_RESISTOR	0.000125	
  #elif (DEVICETYPE == 250)
    #define SHUNT_RESISTOR	0.000250	
  #elif (DEVICETYPE == 125)
    #define SHUNT_RESISTOR	0.000500	
  #else
  #error No valid device type
  #endif
  		




//	--- LOKALE TYPE DEFS - bitte hier dokumentieren-------------------------------

//	--- DEFINITIONEN GLOBALER VARIABLEN - Bitte in Header dokumentieren ----------

//	--- LOKALE VARIABLEN - bitte hier dokumentieren ------------------------------

//	--- LOKALE FUNKTIONS PROTOTYPEN ---------------------------------------------- 

//	--- LOKALE FUNKTIONEN - bitte hier dokumentieren -----------------------------

//	--- GLOBALE FUNKTIONEN - bitte in Header dokumentieren------------------------


void FAST_CURRENT_Exec(uint32_t newvalP, uint32_t newvalM )
{
  static int measCounter;
  static unsigned long avgsumP = 0;
  uint32_t avgvalP;

  if (measCounter < INT32_MAX) measCounter++;


  // Filterlängen in 2er-Potenzen --> Compiler optimiert 
 // avgsumP -= avgsumP / FAST_CURRENT_FILTER;
 // avgsumP += newvalP;
//  avgvalP = avgsumP / FAST_CURRENT_FILTER;

//  static unsigned long avgsumM = 0;
//  uint32_t avgvalM;
  // Filterlängen in 2er-Potenzen --> Compiler optimiert 
//  avgsumM -= avgsumM / FAST_CURRENT_FILTER;
//  avgsumM += newvalM;
//  avgvalM = avgsumM / FAST_CURRENT_FILTER;


  //Berechne Differenzspannung am ADC Eingnag
  double diff;
  diff = (int32_t) newvalP - (int32_t) newvalM; 
  diff = (diff * sys_data.s.values.realVdd)  / 65536;

  //Umrechung auf Strom
  double temp_current;
  temp_current = (diff / I_SENSE_GAIN) /  SHUNT_RESISTOR;
  sys_data.s.values.fast_current = temp_current * (sys_data.s.parameter.batteryCurrentGainCorrectionFaktor / 1000000.0);
 
}

/*************************** End of file ****************************/