This code example shows how to determine a battery voltage without needing to know the PICAXE supply voltage. It can also be applied to any external voltage which is equal or less than the PICAXE supply voltage (Vpsu). The voltage to be read is fed to one of the available ADC input pins.
Determine the supply voltage, using "CALIBADC10 Nref" ...
Nref = ( Vref / Vpsu ) * 1023
Vpsu = ( Vref / Nref ) * 1023
Read the battery voltage, using "READADC10 pin, Nbat" ...
Nbat = ( Vbat / Vpsu ) * 1023
Vpsu = ( Vbat / Nbat ) * 1023
The two Vpsu results are the same so ...
( ( Vref / Nref ) * 1023 ) = ( ( Vbat / Nbat ) * 1023 )
Divide both sides by 1023 ...
Vref / Nref = Vbat / Nbat
Re-order to get Vbat ...
Vbat = ( Vref / Nref ) * Nbat
Vbat = ( Vref * Nbat ) / Nref
For a Vref of 1024mV, Vbat in mV will be ...
Vbat = ( 1024 * Nbat ) / Nref
But 1024*Nbat could exceed 16-bits so we need to adjust that ...
Vbat = ( ( 512 * Nbat ) / Nref ) * 2
Vbat = ( ( 256 * Nbat ) / Nref ) * 4
Vbat = ( ( 128 * Nbat ) / Nref ) * 8
And finally ...
Vbat = ( ( 64 * Nbat ) / Nref ) * 16
Which in PICAXE basic would be ...
Note that the Nref, Nbat and Vbat variables must all be 16-bit word variables. The 'pin' is the ADC pin to which the battery voltage is connected.
Let's test that. Consider a Vpsu of 4.5V, a Vbat of 4.0V, a Vref of 1.024V. That gives an Nbat of 909, an Nref of 232. Using integer maths and rounding down ...
( ( 64 * 909) / 232 ) * 16 = 4000
Bang-on in that particular case, 4000mV, 4.0V.
Consider a Vpsu of 4.75V, a Vbat of 3.25V, a Vref of 1.024V. That gives an Nbat of 699, an Nref of 220 ...
( ( 64 * 699 ) / 220 ) * 16 = 3248
Determine the supply voltage, using "CALIBADC10 Nref" ...
Nref = ( Vref / Vpsu ) * 1023
Vpsu = ( Vref / Nref ) * 1023
Read the battery voltage, using "READADC10 pin, Nbat" ...
Nbat = ( Vbat / Vpsu ) * 1023
Vpsu = ( Vbat / Nbat ) * 1023
The two Vpsu results are the same so ...
( ( Vref / Nref ) * 1023 ) = ( ( Vbat / Nbat ) * 1023 )
Divide both sides by 1023 ...
Vref / Nref = Vbat / Nbat
Re-order to get Vbat ...
Vbat = ( Vref / Nref ) * Nbat
Vbat = ( Vref * Nbat ) / Nref
For a Vref of 1024mV, Vbat in mV will be ...
Vbat = ( 1024 * Nbat ) / Nref
But 1024*Nbat could exceed 16-bits so we need to adjust that ...
Vbat = ( ( 512 * Nbat ) / Nref ) * 2
Vbat = ( ( 256 * Nbat ) / Nref ) * 4
Vbat = ( ( 128 * Nbat ) / Nref ) * 8
And finally ...
Vbat = ( ( 64 * Nbat ) / Nref ) * 16
Which in PICAXE basic would be ...
Code:
CalibAdc10 Nref
ReadAdc10 [i]pin[/i], Nbat
Vbat = 64 * Nbat / Nref * 16
Let's test that. Consider a Vpsu of 4.5V, a Vbat of 4.0V, a Vref of 1.024V. That gives an Nbat of 909, an Nref of 232. Using integer maths and rounding down ...
( ( 64 * 909) / 232 ) * 16 = 4000
Bang-on in that particular case, 4000mV, 4.0V.
Consider a Vpsu of 4.75V, a Vbat of 3.25V, a Vref of 1.024V. That gives an Nbat of 699, an Nref of 220 ...
( ( 64 * 699 ) / 220 ) * 16 = 3248
Last edited: