I want to convert a bunch of uint16_t values from an ADC into floating point voltages.
For this I use a for loop to loop through the uint16_t array and write the values to a float array.
But the float array remains 0 as if no assignment is ever made. Outside of the for loop the conversion works.
And when I step through the program with the debugger, I see reasonable float values but they do not end up being written to the array. Why?
the temporary float value is clearly 1.847:
the temporary array index is clearly 0:
so I expect the adc_voltages[0] to be 1.847 which it is not:
Code:
Global Variables:
volatile uint16_t adc_dma_buffer[SG_MK2_ADC1_CHANNELS * SG_MK2_ADC1_N_SAMPLES];
float adc_voltages[SG_MK2_ADC1_CHANNELS * SG_MK2_ADC1_N_SAMPLES];
Later in the main():
float temp = 0.0f;
uint8_t index = 0;
for(uint8_t i=0; i<8; i++){
temp = BSP_convU1(adc_dma_buffer[i*SG_MK2_ADC1_CHANNELS+0]);
index = i*SG_MK2_ADC1_CHANNELS+0;
adc_voltages[index] = temp; // BSP_convU1(adc_dma_buffer[i*SG_MK2_ADC1_CHANNELS+0]);
adc_voltages[i*SG_MK2_ADC1_CHANNELS+1] = BSP_convU2(adc_dma_buffer[i*SG_MK2_ADC1_CHANNELS+1]);
adc_voltages[i*SG_MK2_ADC1_CHANNELS+2] = BSP_convU3(adc_dma_buffer[i*SG_MK2_ADC1_CHANNELS+2]);
adc_voltages[i*SG_MK2_ADC1_CHANNELS+3] = BSP_internalTemperature(adc_dma_buffer[i*SG_MK2_ADC1_CHANNELS+3]);
}
Where the functions return float:
float BSP_convU1(uint32_t adc_val){
float adc_vsense = SG_MK2_ADC_VREF/4096.0f * (float)adc_val;
return adc_vsense * BSP_CONV_U1_FACTOR + BSP_CAL_U1_OFFSET;
}
Edit:
Thanks for all the comments and good practice hints that I will use from now on. Especially with the usage of 2D arrays.
I was just able to resolve the issue.
I am still not sure why it happened.
"working outside of the loop" was not correct either, it only worked, when BSP_conv_I_MPPT()
was evaluated inside the printf statement directly.
Anyhow, the following code with 2D arrays now works.
if(flag_SDADC_cplt){
flag_SDADC_cplt=0;
for(int i=0; i<SG_MK2_SDADC1_N_SAMPLES; i++){
adc_currents[i][0] = BSP_conv_I_Boost (sdadc_dma_buffer[i][0]);
adc_currents[i][1] = BSP_conv_I_MPPT (sdadc_dma_buffer[i][1]);
adc_currents[i][2] = BSP_conv_I_Solar (sdadc_dma_buffer[i][2]);
// order: adc[sample][channel]
}
printf("DCDC\tMPPT\tPV\n");
printf("%.3fA\t%.3fA\t%.3fA\n", adc_currents[0][0], adc_currents[1][0], adc_currents[2][0]); // order[channel][sample]
}
if(flag_ADC_cplt){
flag_ADC_cplt = 0;
for(int i=0; i<SG_MK2_ADC1_N_SAMPLES; i++){
adc_voltages[i][0] = BSP_convU1(adc_dma_buffer[i][0]);
adc_voltages[i][1] = BSP_convU2(adc_dma_buffer[i][1]);
adc_voltages[i][2] = BSP_convU3(adc_dma_buffer[i][2]);
adc_voltages[i][3] = BSP_internalTemperature(adc_dma_buffer[i][3]);
}
printf("\nPV\tCAN\tBat\tTemp\n");
printf("%.2fV\t%.2fV\t%.2fV\t%.1fC\n", adc_voltages[0][0], adc_voltages[0][1], adc_voltages[0][2], adc_voltages[0][3]);
}