UnexpectedMaker / esp32s3

Assorted files for my ESP32-S3 development boards
193 stars 29 forks source link

update get_battery_voltage with clear calculation #2

Closed dgriswo closed 2 years ago

dgriswo commented 2 years ago

Updates the get_battery_voltage function to return values based on expanded mathematical calculation. This can be ported to any board by changing the R1 and R2 variables.

In CircuitPython, the voltage on the pin is calculated by the value divided by the ADC resolution multiplied by the reference voltage. It uses a 16-bit ADC, regardless of what the board supports. So Vin = adc.value / (2^16-1) * 3.3

One important note about this 16-bit range is that it applies even if your board’s ADC has a different resolution (like 10 or 12 bits). Using 16-bits as a base resolution is handy to make code work across many different boards but be aware you might not actually be getting 16-bits of resolution from your ADC. Check your board’s documentation to see the true resolution of its ADC. https://learn.adafruit.com/circuitpython-basics-analog-inputs-and-outputs/analog-to-digital-converter-inputs

Given the formula for voltage dividers, Vout=(Vsource R2) / (R1 + R2), we can re-write to Vsource = Vout (R1 + R2) / R2. For the S3 line, R1 is 442000 ohm, and R2 is 160000 ohm.

Combine the two is Vsource = adc.value / (2^16-1) 3.3 ( 442000 + 160000 ) / 160000, which simplifies to adc.value / 5278.1637, which is approximately equal to the original code (5371).

UnexpectedMaker commented 2 years ago

Thanks mate!