Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sudo raspi-config #Enable Interfacing Options>I2C
- sudo apt-get install i2c-tools #Install i2c-tools
- nano ~/ups.py #Make a new python script and add the code below
- crontab -e
- /5 * * * * python /home/pi/ups.py > /dev/null 2>&1 #Add to crontab. Run script every 5 min.
- 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)
- # 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()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement