#include "main.h"
#include "voltage_meas.h"
#include "relais.h"
#include <stdlib.h>
#include <stdio.h>



uint32_t voltageUin;
uint32_t voltageUout;
uint32_t voltageDrop;

#define	VOLTAGE_DIVIDER_12V		6
#define VOLTAGE_DROP_U_LIMIT	90 //mV ca. 30 mV Messfehler + 60mV bei 150A 
#define VOLTAGE_DROP_T_LIMIT	1000

uint32_t dropLimitCounter=0;


void VOLTAGE_MEAS_Exec(uint32_t adcValUin, uint32_t adcValUout)
{

  int32_t vuin;
  vuin = adcValUin * VREF;
  vuin = vuin / 65635;
  vuin = vuin * VOLTAGE_DIVIDER_12V; //Divider ür 12V Version
  voltageUin = vuin;


  int32_t vuout;
  vuout = adcValUout * VREF;
  vuout = vuout / 65635;
  vuout = vuout * VOLTAGE_DIVIDER_12V; //Divider ür 12V Version
  voltageUout = vuout;
  
  voltageDrop = abs((int32_t)voltageUin - (int32_t)voltageUout);

  if ((RELAIS_GetState() == 1) && (voltageDrop > VOLTAGE_DROP_U_LIMIT))
  {
	if (dropLimitCounter < VOLTAGE_DROP_T_LIMIT) dropLimitCounter++;
	printf("voltage in= %d, out= %d, drop %d\r\n", voltageUin, voltageUout,  voltageDrop);
  }
  else
  {
	if (dropLimitCounter > 0) dropLimitCounter--;
  }
  
}


uint32_t VOLTAGE_MEAS_GetLimitAlarm(void)
{
  if (dropLimitCounter == VOLTAGE_DROP_T_LIMIT) {
	return 1;
  }
  else {
	return 0;
  }

}

void VOLTAGE_MEAS_ResetCounter(void)
{
  dropLimitCounter = 0;
	
  }