Monday 19 September 2016

Measuring battery voltage with ESP8266

If you run IoT devices on batteries then it would be nice to know how much capacity is left on the battery, so you can change it before the device dies. Easiest way to do this is measuring battery voltage. Esp8266 has adc, but it's only from zero to one volt. The correct way would probably be to use Non-Inverting Op-Amp Level Shifter, but that would require many components and negative voltage. Easier approach is to just use voltage divider and just get the maximum voltage to acceptable range.

Using a calculator we get resistor values of 120kOhm and 39kOhm for getting 4.1 volts to 1 volt. For a low voltage of 3 volts these resistors would give 0.736 volts. So we are using 0.264 of esp8266 adc range of 0 - 1 volts. Adc is 10 bits so we have 0.264*1024=270 different values, even with some noise that should be enough for our purpose.



I made a small lua script that reads adc every minute and then posts the result with mqtt. Then used mosquitto_sub from Mosquitto to subscribe to that topic and log the messages.
mosquitto_sub -h roope.local -t /esp/battery | while read line; do echo -n $(date -Ins); echo -e "\t$line"; done | tee esp_battery.log Where roope.local is the mqtt broker machine.

Measurements and calculations can be found here https://docs.google.com/spreadsheets/d/1t18V1jrTRbj8nI5lrpctb8Fs9KzmpQ9O05dR5AeF37k/edit?usp=sharing. Esp_battery tab has raw data and formula has cleaned up data and formula.

I used google sheets linest function to calculate a function to get voltage from adc values, voltage=0.003539154715*adc+0.3756228338.

adcvoltage
10003.914777549
9003.560862077
8003.206946606
7002.853031134
6002.499115663

One problem for voltage divider is that it uses some power all the time. I should probably check how much that is, and if it considerably affects how long the battery will last. But for my next battery powered project, it will most likely report battery status also.


No comments:

Post a Comment