2023-02-28 14:00:54 +00:00
|
|
|
#include <xc.h>
|
|
|
|
|
|
|
|
#include "measure.h"
|
|
|
|
#include "mcc_generated_files/mcc.h"
|
|
|
|
|
|
|
|
#define VOLTAGE_CHANNEL 0x5
|
|
|
|
#define CURRENT_CHANNEL 0x6
|
2023-02-28 15:15:58 +00:00
|
|
|
#define ADC_RESOLUTION (1024 - 1)
|
2023-02-28 14:00:54 +00:00
|
|
|
#define ADC_REFH 3300
|
|
|
|
#define GAIN 66
|
|
|
|
#define RESISTOR 3
|
|
|
|
|
|
|
|
// Number of samples to do the averaging during measures
|
|
|
|
#define AVERAGE_SAMPLES 8
|
|
|
|
|
|
|
|
void adc_init(void)
|
|
|
|
{
|
|
|
|
// TODO -> complete adc initialisation
|
2023-02-28 15:15:58 +00:00
|
|
|
//offsetCurrent = measure_current(0);
|
2023-02-28 14:00:54 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Read one ADC channel. This function is only
|
|
|
|
* local to this file.
|
|
|
|
*
|
|
|
|
* @param channel : the channel to be measured
|
|
|
|
* @return the ADC read value
|
|
|
|
*/
|
|
|
|
static uint16_t measure_adc(uint8_t channel)
|
|
|
|
{
|
|
|
|
return (uint16_t) (ADC_GetConversion(channel));
|
|
|
|
}
|
|
|
|
|
2023-02-28 15:15:58 +00:00
|
|
|
|
|
|
|
|
2023-02-28 14:00:54 +00:00
|
|
|
uint16_t measure_voltage()
|
|
|
|
{
|
2023-02-28 15:15:58 +00:00
|
|
|
uint32_t sum = 0;
|
|
|
|
|
|
|
|
for(int i = 0; i < AVERAGE_SAMPLES; i++) {
|
|
|
|
sum += measure_adc(VOLTAGE_CHANNEL);
|
|
|
|
}
|
|
|
|
sum /= AVERAGE_SAMPLES;
|
2023-03-03 12:11:20 +00:00
|
|
|
sum = (sum * ADC_REFH) / ADC_RESOLUTION;
|
2023-02-28 15:15:58 +00:00
|
|
|
return (uint16_t)(sum);
|
2023-02-28 14:00:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
uint16_t measure_current(uint16_t offset)
|
|
|
|
{
|
2023-02-28 15:15:58 +00:00
|
|
|
uint32_t sum = 0;
|
|
|
|
for(int i = 0; i< AVERAGE_SAMPLES; i++){
|
|
|
|
sum += measure_adc(CURRENT_CHANNEL);
|
|
|
|
}
|
2023-03-03 12:11:20 +00:00
|
|
|
uint32_t m = (sum / AVERAGE_SAMPLES); // m is bits
|
|
|
|
m = (m * ADC_REFH) / ADC_RESOLUTION; // m is mV
|
|
|
|
m *= 1000; // m is uV
|
2023-02-28 15:15:58 +00:00
|
|
|
m /= GAIN;
|
2023-03-03 12:11:20 +00:00
|
|
|
m /= RESISTOR; // m is uA
|
2023-02-28 15:15:58 +00:00
|
|
|
if(m <= offset){
|
2023-02-28 14:00:54 +00:00
|
|
|
m = 0;
|
2023-02-28 15:15:58 +00:00
|
|
|
} else {
|
|
|
|
m -= offset;
|
2023-02-28 14:00:54 +00:00
|
|
|
}
|
2023-02-28 15:15:58 +00:00
|
|
|
|
|
|
|
return (uint16_t)m;
|
2023-02-28 14:00:54 +00:00
|
|
|
}
|