forked from mezl/pi-battery-widget
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpi-battery-reader.py
executable file
·60 lines (46 loc) · 1.5 KB
/
pi-battery-reader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
*** RED REACTOR - Copyright (c) 2022
*** Author: Pascal Herczog
*** This code is designed for the RED REACTOR Raspberry Pi Battery Power Supply
*** Example code provided without warranty
*** Provides Voltage and Current readings to Battery Icon
*** Filename: pi-battery-reader.py
*** PythonVn: 3.8, 32-bit
*** Date: January 2022
"""
from ina219 import INA219 # This controls the battery monitoring IC
from ina219 import DeviceRangeError # Handle reading errors
# Constants
# RED REACTOR I2C address
I2C_ADDRESS = 0x40
# RED REACTOR Measurement Shunt (defined in Ohms)
SHUNT_OHMS = 0.05
# Set Current Measurement Range
MAX_EXPECTED_AMPS = 5.5
# ADC Default
# ADC*12BIT: 12 bit, conversion time 532us (default).
# Verify that RED REACTOR is attached, else return defaults
try:
# Include busnum=1 for Bullseye
bat_reader = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, busnum=1)
bat_reader.configure(bat_reader.RANGE_16V)
voltage = bat_reader.voltage()
current = bat_reader.current()
except DeviceRangeError:
# Current out of range for the RedReactor
voltage = 4.5
current = 6000.0
except RuntimeError as e:
# Failed to access I2C bus but there is power
voltage = 0.0
current = 0.0
except OSError:
"""RED REACTOR IS NOT Attached, returning defaults"""
# 0v means No Red Reactor fitted
print("0.000|0.00")
exit(1)
finally:
# Read by sscanf(buffer, "%f|%f",&vv, ¤t);
print("{:.3f}|{:.2f}".format(voltage, current))