-

CommentStreams:764d7138a34fa5fbf3293982d7ad839b

From Geekworm Wiki
< CommentStreams:D4c62d33cd6d4d0fdfeddae90e39e633
Revision as of 15:17, 22 February 2020 by 204.174.159.1 (talk) (Migrated reply #780)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

sudo raspi-config # Enable Interfacing Options>I2C sudo apt-get install i2c-tools # Install i2c-tools nano ~/ups.py # Make a new python script

... import struct import smbus import sys import time import os

lowest = 60

def readVoltage(bus):

 "This function returns as float the voltage from the Raspi UPS Hat via the provided SMBus object"
 address = 0x36
 read = bus.read_word_data(address, 2)
 swapped = struct.unpack("<H", struct.pack(">H", read))[0]
 voltage = swapped * 78.125 /1000000
 return voltage

def readCapacity(bus):

 "This function returns as a float the remaining capacity of the battery connected to the Raspi UPS Hat via the provided SMBus object"
 address = 0x36
 read = bus.read_word_data(address, 4)
 swapped = struct.unpack("<H", struct.pack(">H", read))[0]
 capacity = swapped/256
 return capacity

def shutdown():

 os.system("sudo shutdown -h now")

bus = smbus.SMBus(1) # 0 = /dev/i2c-0 (port I2C0), 1 = /dev/i2c-1 (port I2C1) print "Voltage:%5.2fV" % readVoltage(bus) print "Battery:%5i%%" % readCapacity(bus)

  1. Only check if we are low

if readCapacity(bus) <= lowest:

 first = readCapacity(bus)
 time.sleep(5)
 second = readCapacity(bus)
 # If battery capacity is dropping
 if first > second:
   shutdown()

...

crontab -e

  • /5 * * * * python /home/pi/ups.py > /dev/null 2>&1 #Add to crontab. Run script every 5 min.