#include <stdint.h>
#include <stdbool.h>
#include <xc.h>


#include "misc.h"
#include "userComm.h"
#include "userGEN.h"
#include "userADC.h"
#include "../mcc_generated_files/pin_manager.h"
#include "../mcc_generated_files/adc1.h"

#define apply_Q(x) ((x)>>4)                     //number determines length of IIR filter

uint32_t current;


uint16_t DRV_ReadCurrent(void)                                                  //convetrs ADC data to current
{
    int32_t ADCRawData;
    int32_t ADCCurrent;
    
    ADCRawData = apply_Q( current );
    
    ADCCurrent = (ADCRawData * 4883);
    if (ADCCurrent - 500000 >= 0) 
    {
        ADCCurrent -= 500000;
    }else{
        ADCCurrent = 0;
    }

    ADCCurrent = ADCCurrent / 185;
    
    return (uint16_t)ADCCurrent;
}

void DRV_ADCStart(void)
{
    //AD1CHS0 = 54;
    AD1CON1bits.SAMP = 1;    
}


void ADC_ISR(uint8_t bufferID)
{
    uint8_t ReadBufferID = (~bufferID) & 0x01;
    
    uint8_t i;
    for(i=0;i<8;i++)                                                //Readout voltages from buffer and put into
    {                                                               //exponential filter
        current -= apply_Q( current );
        current += ADC1_ConversionResultGetOnIndex( i + (8*ReadBufferID) );           //buffer index for specific ADC channel is corresponeding with schematic
                                                                          //2 buffers, adressed VoltageType + BaseAddress which is ReadBufferID
    }
}

