Skip to content

Instantly share code, notes, and snippets.

@asterix24
Last active March 27, 2021 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asterix24/a636711b819fb0f3d6dd9caa1c9dbc8b to your computer and use it in GitHub Desktop.
Save asterix24/a636711b819fb0f3d6dd9caa1c9dbc8b to your computer and use it in GitHub Desktop.
Simple script to show battery info from UPS HAT for rapsberry pi, and shutdonw graceful the rasberry when battery is low level.
#!/bin/bash
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2021 Daniele Basile <asterix24@gmail.com>
#
# Note: to use this script you should before enable the i2c subsystem of
# raspberry, by the rasp-config.Other than that you should install the i2c utils script package.
# Here you could find more info: https://raspberrypiwiki.com/images/6/6f/How-to-use-via-i2c.pdf.
# You can add this scritp to crontab so you could check if the power supply fall down.
# Here is a little example, we run scritp every 2min, remember to do this with root user.
# # m h dom mon dow command
# */2 * * * * /usr/local/bin/battery.sh
I2CGET=/usr/sbin/i2cget
DATA=$(${I2CGET} -f -y 1 0x36 2 w)
RAW=$(printf "%d\n" $(echo "${DATA}" | sed -E "s/0x([a-f0-9]{2})([a-f0-9]{2})/0x\2\1/"))
VOLT=$(echo "scale=2; ${RAW}*78.125/1000000" | bc -l)
DATA=$(${I2CGET} -f -y 1 0x36 4 w)
RAW=$(printf "%d\n" $(echo "${DATA}" | sed -E "s/0x([a-f0-9]{2})([a-f0-9]{2})/0x\2\1/"))
LEVEL=$(echo "scale=2; ${RAW}/256" | bc -l)
if [ x"$1" == "-h" ]; then
echo "usage $0 [-p show battery level %] [-v show battery voltage V]"
fi
[ x"$1" == x"-p" ] && echo "${LEVEL}%"
[ x"$1" == x"-v" ] && echo "${VOLT}V"
if [ $# -lt 1 ]; then
echo "Battery Voltage: ${VOLT}V"
echo "Battery Capacity: ${LEVEL}%"
fi
# if battery level goes under 25%, shutdown the system gracefull, to avoid
# filesystem damages.
if [ $(echo "${LEVEL} < 25" | bc) == 1 ]; then
echo "low battery level shutdown.."
/usr/sbin/shutdown -h now
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment