You need to enable JavaScript to run this app. STM32(arm-none-eabi-gcc)环境下for循环内float数组赋值失败问题
优惠活动
大模型
产品
解决方案
定价
更多

STM32(arm-none-eabi-gcc)环境下for循环内float数组赋值失败问题

ADC采集值转浮点电压写入数组失败问题及解决

我需要将ADC采集的一批uint16_t类型数值转换为浮点型电压值,因此采用for循环遍历uint16_t数组,将转换后的值写入float数组,但float数组始终保持为0,仿佛赋值操作从未执行,而在for循环外执行转换操作可以正常生效。

使用调试器单步运行程序时,可见临时float变量已经得到合理的转换值1.847,临时数组索引也明确为0,但adc_voltages[0]并未被写入预期的1.847,仍然为0。

相关代码

全局变量定义

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];

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]);
}

转换函数实现

转换函数返回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;
}

问题解决与最终代码

此前所说的“循环外可以正常工作”的表述不准确,实际上只有直接在printf语句内执行BSP_conv_I_MPPT()运算时才会正常输出结果。最终采用二维数组重构代码后问题解决,可正常运行的代码如下:

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]);
}

内容的提问来源于stack exchange,提问作者mnemocron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 20:48:03