Advertisement
Brendan205

Raspi UPS HAT auto shutdown

Feb 21st, 2020
1,350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. sudo raspi-config #Enable Interfacing Options>I2C
  2. sudo apt-get install i2c-tools #Install i2c-tools
  3. nano ~/ups.py  #Make a new python script and add the code below
  4. crontab -e
  5. /5 * * * * python /home/pi/ups.py > /dev/null 2>&1 #Add to crontab. Run script every 5 min.
  6.  
  7. import struct
  8. import smbus
  9. import sys
  10. import time
  11. import os
  12.  
  13. lowest = 60
  14.  
  15. def readVoltage(bus):
  16.   "This function returns as float the voltage from the Raspi UPS Hat via the provided SMBus object"
  17.   address = 0x36
  18.   read = bus.read_word_data(address, 2)
  19.   swapped = struct.unpack("<H", struct.pack(">H", read))[0]
  20.   voltage = swapped * 78.125 /1000000
  21.   return voltage
  22.  
  23. def readCapacity(bus):
  24.   "This function returns as a float the remaining capacity of the battery connected to the Raspi UPS Hat via the provided SMBus object"
  25.   address = 0x36
  26.   read = bus.read_word_data(address, 4)
  27.   swapped = struct.unpack("<H", struct.pack(">H", read))[0]
  28.   capacity = swapped/256
  29.   return capacity
  30.  
  31. def shutdown():
  32.   os.system("sudo shutdown -h now")
  33.  
  34. bus = smbus.SMBus(1)  # 0 = /dev/i2c-0 (port I2C0), 1 = /dev/i2c-1 (port I2C1)
  35. print "Voltage:%5.2fV" % readVoltage(bus)
  36. print "Battery:%5i%%" % readCapacity(bus)
  37.  
  38. # Only check if we are low
  39. if readCapacity(bus) < lowest:
  40.   first = readCapacity(bus)
  41.   time.sleep(5)
  42.   second = readCapacity(bus)
  43.   # If battery capacity is dropping
  44.   if first > second:
  45.     shutdown()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement