After I completed the circuitry to power my raspberry pi from a battery pack, I wanted a way to display the voltage of the battery pack, and be able to access the voltage level from the raspberry pi, so it can shutdown automatically when critical voltage levels are reached to prevent damage to the filesystem or draining the battery too much.
Our Pi can stand at most 5V per input pin, so how do we measure voltages like the 7.4V of our battery and above (if its full, it has more than 7.4V)? We have to scale the highest expected voltage down to 5V! The easiest way to do this is by using a voltage divider. Suppose the 9v-battery in the schematic below is our battery, and the arduino is powered over USB. We connect GND of both and divide the 9V of the battery by using a voltage divider. If both resistors in the schematic below are equal, we effectively halve the voltage. Remember the formula for voltage dividers (without load):
In our case, that means if the battery is full and has 9V:
So the maximal expected voltage at our analog-in is 4.5V!
By using the arduino-function analogRead(A0), we get a value between 0 and 1023, which represents the voltage scale from 0-5V. We know that whatever we read will be halve of the actual external voltage, so to convert this value back to the actual voltage:
int sensorValue = analogRead(A0); voltage = sensorValue * (10.0 / 1023.0)
Now this can be put into a nice little script to output this value over serial to the Raspberry Pi, and display it somewhere. I chose to use a 1.44 Inch Spi Tft Lcd Color Screen St7735 with 128×160 pixels and wrote some code to save and display measurements at certain time-intervalls in a rolling fashion, which results in this: