This repository has been archived on 2024-01-25. You can view files and clone it, but cannot push or open issues or pull requests.
Solar-Panel/solar_panel.X/measure.c

65 lines
1.3 KiB
C
Raw Normal View History

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;
sum = (sum * ADC_RESOLUTION) / ADC_REFH;
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);
}
uint32_t m = (sum / AVERAGE_SAMPLES);
m /= GAIN;
m /= RESISTOR;
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
}