Skip to content

Commit

Permalink
fix: wrong avg calc
Browse files Browse the repository at this point in the history
  • Loading branch information
luftaquila committed Oct 28, 2024
1 parent dbc116c commit 77f70da
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
2 changes: 1 addition & 1 deletion device/firmware/Core/Inc/energymeter.h
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ enum {
#define VOLTAGE_DIVIDER_RATIO_5VREF 2.0f

#define ADC_CAL_CNT 10
#define ADC_AVG_CNT 10
#define ADC_AVG_CNT 20

#define ADC_RES 12 // ADC bit resolution

Expand Down
25 changes: 11 additions & 14 deletions device/firmware/Core/Src/energymeter_record.c
Original file line number Diff line number Diff line change
Expand Up @@ -52,34 +52,31 @@ void energymeter_record(char *filename) {

while (TRUE) {
// seems like that the avgerage calculation has no effect
uint32_t adc_avg[ADC_CH_CNT] = { 0, };
int32_t adc_avg_hv_voltage;
int32_t adc_avg_hv_current;

// 10 ms timer
if (timer_flag) {
// reset all average buffers
adc_avg[ADC_LV_VOLTAGE] = 0;
adc_avg[ADC_HV_CURRENT] = 0;
adc_avg[ADC_HV_VOLTAGE] = 0;
adc_avg[ADC_TEMP] = 0;
adc_avg_hv_voltage = 0;
adc_avg_hv_current = 0;

// calculate average values
for (int i = 0; i < ADC_AVG_CNT; i++) {
HAL_ADC_Start_DMA(&hadc1, adc, ADC_CH_CNT);
while (adc_flag != TRUE); // poll until ADC conv done; nothing to do

adc_avg[ADC_LV_VOLTAGE] += adc[ADC_LV_VOLTAGE];
adc_avg[ADC_HV_CURRENT] += adc[ADC_HV_CURRENT];
adc_avg[ADC_HV_VOLTAGE] += adc[ADC_HV_VOLTAGE];
adc_avg[ADC_TEMP] += adc[ADC_TEMP];
adc_avg_hv_voltage += (int16_t)(adc[ADC_HV_VOLTAGE]);
adc_avg_hv_current += (int16_t)(adc[ADC_HV_CURRENT]);

for (int i = 0; i < 10000; i++); // delay for ADC conversion
adc_flag = FALSE;
}

log.timestamp = HAL_GetTick(); // boot sequence take ~700ms; take grant for the error
log.packet.record.hv_voltage = adc_avg[ADC_HV_VOLTAGE] / ADC_AVG_CNT;
log.packet.record.hv_current = adc_avg[ADC_HV_CURRENT] / ADC_AVG_CNT;
log.packet.record.lv_voltage = adc_avg[ADC_LV_VOLTAGE] / ADC_AVG_CNT;
log.packet.record.temperature = adc_avg[ADC_TEMP] / ADC_AVG_CNT;
log.packet.record.hv_voltage = (uint16_t)(int16_t)(adc_avg_hv_voltage / ADC_AVG_CNT);
log.packet.record.hv_current = (uint16_t)(int16_t)(adc_avg_hv_current / ADC_AVG_CNT);
log.packet.record.lv_voltage = adc[ADC_LV_VOLTAGE];
log.packet.record.temperature = adc[ADC_TEMP];

// checksum calculation
log.checksum = 0;
Expand Down

0 comments on commit 77f70da

Please sign in to comment.