Search code examples
cstm32data-conversionadc

How to convert reading ADC Value to Float?


I want to convert ADC Values to float numbers. This is my code:

uint32_t ADCValue;
char str[15];

          ADCValue = HAL_ADC_GetValue(&hadc1);
          ADCValue=ADCValue*3.3/4095;
          sprintf(str, "%d", Voltage);
          HAL_UART_Transmit(&huart2, (uint8_t*)(&str), 6, 100);
          HAL_UART_Transmit(&huart2, (uint8_t*) "\n\r", 2, 100);
          HAL_Delay(500);

I am reading value of 4095 at 3.3V but I am transmitting 3 to buffer. I want to transmit exact value of voltage.


Solution

  • There is no apparent reason why you need to use float numbers here in the first place. They are needlessly slow. Simply do this:

    uint32_t millivolts = ADCValue*3300/4095.
    

    For an input of 4095, you get the result 3299mV. This is possibly more accurate than what you would get through float numbers, because of floating-point inaccuracy.