Anth's Computer Cave

Build a dual-battery monitor for Arduino, Part Two

Yesterday we built the circuitry for the battery monitor and loaded, tested and adjusted the Arduino sketch.

Today we'll access the battery readings from Python on a Raspberry Pi so you can use the data from within your own programs.

Copy and paste the code below into a file named on your Raspberry Pi. You can also download the full setup folder including yesterday's Arduino sketch from here.

#AAIMI Battery Monitor
#Part of the AAIMI Project
#By Anthony Hartup

import serial
import time

battery1 = 0.0
battery2 = 0.0

arduino = serial.Serial('/dev/ttyUSB0', 9600)

def get_float_string(n):
    return str(''.join(d for d in n if d.isdigit() or d == '.'))

def power_check(sensor):
    global battery1, battery2
    if sensor == 'a':
    elif sensor == 'b':
    while True:
            raw_power = arduino.readline()
            power = get_float_string(raw_power)
            if sensor == 'a':
                battery1 = float(power)
                return power
            elif sensor == 'b':
                battery2 = float(power)
                return power                

You may need to change the "ttyUSB0" port in line 12 in the code above. See How to configure a serial connection between an Arduino and a Raspberry Pi to learn more.

Run the module

From a terminal, navigate to the folder containing the file and type sudo python.

When Python loads type import aaimi_battery_monitor as abm.

Now type abm.power_check('a').

You should see the voltage for your first battery.

To see the voltage for the second battery type abm.power_check('b').

Now, here we are only using the module in a Python shell, but you can import this module into any of your Python programs and call it in the same way as the examples above. You can then decide how your program should react to the voltage levels.



Previous: Dual battery monitor



Leave a comment.

There are currently no comments for this article.

Leave a comment on this article