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/measure.c

70 lines
1.6 KiB
C
Raw Permalink Normal View History

2023-02-28 15:00:54 +01:00
#include <xc.h>
#include "measure.h"
#include "mcc_generated_files/mcc.h"
#define VOLTAGE_CHANNEL 0x5
#define CURRENT_CHANNEL 0x6
2023-02-28 16:15:58 +01:00
#define ADC_RESOLUTION (1024 - 1)
2023-02-28 15:00:54 +01:00
#define ADC_REFH 3300
#define GAIN 66
#define RESISTOR 3
// Number of samples to do the averaging during measures
#define AVERAGE_SAMPLES 8
2023-03-18 16:05:24 +01:00
void adc_init(void) {
2023-02-28 15:00:54 +01:00
// TODO -> complete adc initialisation
2023-02-28 16:15:58 +01:00
//offsetCurrent = measure_current(0);
2023-02-28 15:00:54 +01:00
}
/**
* Read one ADC channel. This function is only
* local to this file.
2023-03-18 16:05:24 +01:00
* This function make the average on samples
2023-02-28 15:00:54 +01:00
*
* @param channel : the channel to be measured
2023-03-18 16:05:24 +01:00
* @return the ADC read value with an average
2023-02-28 15:00:54 +01:00
*/
2023-03-17 11:46:31 +01:00
static uint16_t measure_adc(uint8_t channel) {
2023-03-18 16:05:24 +01:00
uint32_t value = 0;
// Make an average
for(int i = 0; i < AVERAGE_SAMPLES; i++) {
value += (uint16_t) (ADC_GetConversion(channel));
}
value /= AVERAGE_SAMPLES;
return (uint16_t) (value);
2023-02-28 15:00:54 +01:00
}
2023-02-28 16:15:58 +01:00
2023-03-17 11:46:31 +01:00
/**
2023-03-18 16:05:24 +01:00
* Measure voltage
2023-03-17 11:46:31 +01:00
* @return
*/
uint16_t measure_voltage() {
2023-03-18 16:05:24 +01:00
uint32_t value = measure_adc(VOLTAGE_CHANNEL);
2023-03-17 11:46:31 +01:00
// Convert sum from bits to mV
2023-03-18 16:05:24 +01:00
value = (value * ADC_REFH) / ADC_RESOLUTION;
return (uint16_t)(value);
2023-02-28 15:00:54 +01:00
}
2023-03-18 16:05:24 +01:00
/**
*
* @param offset
* @return
*/
2023-03-17 11:46:31 +01:00
uint16_t measure_current(uint16_t offset) {
2023-03-18 16:05:24 +01:00
uint32_t value = measure_adc(CURRENT_CHANNEL);
// Convert from bits to uA
value = (value * ADC_REFH) / ADC_RESOLUTION; // [mV]
value *= 1000; // [uV]
value /= GAIN; // [uV]
value /= RESISTOR; // [uA]
2023-02-28 16:15:58 +01:00
2023-03-18 16:05:24 +01:00
// Return value without offset or null if it's too low
if(value > offset) return (uint16_t)(value-offset);
return 0;
2023-02-28 15:00:54 +01:00
}