Here’s a short little post to show something I made a few years ago. It’s a simple, tiny board with a couple of resistors that is used to measure the input voltage. It uses a simple voltage divider to reduce the voltage from the raw input pin and allow the conveniently close analog pin to read it.
I don’t remember which resistor values I used but you can determine that for yourself using the simple formula below. The key is to think about the max battery value that could be plugged in and the maximum IO voltage on the pin. So if you’re using a standard UNO R3, the max is about 12V and the max IO voltage we would want is 5V. In reality it can handle slightly more than 5V but that wouldn’t be useful to us since the pin can only measure up to 5V. If you were using a clone you should look up those two numbers first.
For any given combination of vin and Vout, there are a ton of combinations of r1 and r2 to give you want you want. But there’s a tradeoff. You want to choose higher values because they will draw a smaller current and it will be more efficient. But you want to choose lower values because they will be less susceptible to noise. You also want to put in some safety factor just in case but you don’t want to put too much in because that will reduce your voltage resolution.
For a 12V max Vin and 5V max Vout, using normal resistors I had laying around, I chose R2 = 10k and R1 = 20k. This gives me a max output of 4V on a 12V input. Below is the code necessary to use this. Replace the 5 with the analog voltage, replace 1024 with the highest reading possible if using something other than an 10 bit DAC, and replace 10 and 20 with your resistor values.
float voltage_input = (analogRead(0) * 5 / 1024) * ((20+10)/10);
Here’s a screenshot of the board file. It really is as simple as could be. If you really want the board file for some reason, leave a comment and I’ll post it.