diff --git a/solar_panel.X/main.c b/solar_panel.X/main.c index 0dbb396..537804a 100644 --- a/solar_panel.X/main.c +++ b/solar_panel.X/main.c @@ -56,6 +56,8 @@ void main(void) Lcd_Init(); adc_init(); + uint16_t offsetCurrent = 0; + offsetCurrent = measure_current(offsetCurrent); // If using interrupts in PIC18 High/Low Priority Mode you need to enable the Global High and Low Interrupts // If using interrupts in PIC Mid-Range Compatibility Mode you need to enable the Global and Peripheral Interrupts @@ -82,10 +84,10 @@ void main(void) char msg[MAX_COL+1]; //LCD_2x16_WriteCmd(0x01); // clear display - snprintf(msg, MAX_COL+1, "U = %4i [mV] ", valueV); + snprintf(msg, MAX_COL+1, "U = %04u [mV] ", valueV); LCD_2x16_WriteMsg(msg,0); - snprintf(msg, MAX_COL+1, "I = %4i [uA] ", valueI); + snprintf(msg, MAX_COL+1, "I = %04u [uA] ", valueI); LCD_2x16_WriteMsg(msg,1); } diff --git a/solar_panel.X/measure.c b/solar_panel.X/measure.c index 8f78694..fc8a60c 100644 --- a/solar_panel.X/measure.c +++ b/solar_panel.X/measure.c @@ -5,7 +5,7 @@ #define VOLTAGE_CHANNEL 0x5 #define CURRENT_CHANNEL 0x6 -#define ADC_RESOLUTION 4096 - 1 +#define ADC_RESOLUTION (1024 - 1) #define ADC_REFH 3300 #define GAIN 66 #define RESISTOR 3 @@ -13,14 +13,10 @@ // Number of samples to do the averaging during measures #define AVERAGE_SAMPLES 8 -uint16_t samplesVoltage[AVERAGE_SAMPLES]; -uint16_t samplesCurrent[AVERAGE_SAMPLES]; - - void adc_init(void) { // TODO -> complete adc initialisation - offsetCurrent = measure_current(0); + //offsetCurrent = measure_current(0); } @@ -36,20 +32,34 @@ static uint16_t measure_adc(uint8_t channel) return (uint16_t) (ADC_GetConversion(channel)); } + + uint16_t measure_voltage() { - uint16_t m = measure_adc(VOLTAGE_CHANNEL); - m /= 20; // TODO Explain why 20 - return m; + 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); } uint16_t measure_current(uint16_t offset) { - uint16_t m = measure_adc(CURRENT_CHANNEL); - m -= offset; - if(m <= 0){ - m = 0; - } + 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; - return m; + m /= RESISTOR; + if(m <= offset){ + m = 0; + } else { + m -= offset; + } + + return (uint16_t)m; } \ No newline at end of file diff --git a/solar_panel.X/measure.h b/solar_panel.X/measure.h index d953cf1..2a019c3 100644 --- a/solar_panel.X/measure.h +++ b/solar_panel.X/measure.h @@ -8,7 +8,7 @@ #include -static uint16_t offsetCurrent; + /** * Initialize ADC and pins for measuring current and voltage