Im reading the voltage applied to my microcontroller using the internal voltage reference. Here the topic is talked, and there are some working examples. Im NOT using this examples, im using my own library to do this.
In short, works like this:
- Microcontroller has fixed internal voltaje reference of 2.048v that can be read
- Reading this value with the ADC will give a value from 0-255 (im using 8 bit ADC for efficiency)
- Depending on the value read, you can calculate the voltage at the Vcc pin
- Math is like this:
Vcc_voltage = ADC_MAX_VALUE * VREF_VOLTAGE / adc_value
- Vcc_voltage: Voltage calculated at the VCC input of the microcontroller
- ADC_MAX_VALUE: the maximum value that the ADC could give (CONSTANT: 255 in this case)
- VREF_VOLTAGE: voltage of the internal fixed reference (CONSTANT: 2.048v in this case)
- adc_value: value read by the ADC at the internal voltage reference (VARIABLE: from 0 to 255)
So the calculation result:
Vcc_voltage = 255 * 2.048 / adc_value
In order not to use floats, I multiply the VREF_VOLTAGE * 1000. New calculation:
Vcc_voltage = 255 * 2048 / adc_value
Vcc_voltage = 522240 / adc_value
And this is where im stuck. Im running out of flash, and im optimizing every part of the code. At the moment this is a "int32" division with a int16 result".
I think this could be reduced by some "binary trick", some wise programmer advice or approaching the formula from a different point of view.