"""
read_ina219_pyb.py
Use the RPi Pico to read voltage, current, and power from an INA219
Module over I2C using the pyb_ina219 MicroPython library
"""
import time # Standard Python module used for sleep()
from ina219 import INA219
from ina219 import DeviceRangeError
from machine import I2C, Pin
# The INA219 is connected to I2C on pins GP27 (SCL) and GP26 (SDA).
I2C_BUS = I2C(scl=Pin(27), sda=Pin(26))
# Value of shunt used in the INA219 module
SHUNT_OHMS = 0.1
# Expected amps is 50mA, so set max to 100mA
MAX_EXPECTED_AMPS = 0.1
# INA219 class constructor object
ina219_obj = INA219(SHUNT_OHMS, I2C_BUS, MAX_EXPECTED_AMPS)
# Set calibration to 16V 400mA to maximize resolution.
# This sets the ADC configuration to 12-bit, 1 sample, continuous mode
ina219_obj.configure(ina219_obj.RANGE_16V, ina219_obj.GAIN_1_40MV)
print("DC Voltage, Current, and Power:")
# measure and display loop
while True:
try:
# Read values
bus_voltage_V = ina219_obj.voltage # voltage in V on the load side V-
shunt_voltage_V = ina219_obj.shunt_voltage # voltage in V across the shunt V+ and V-
loadVoltage_V = ina219_obj.supply_voltage # voltage in V for bus supply
current_mA = ina219_obj.current # current in mA
power_W = ina219_obj.power # power in Watts
# Convert shunt voltage from Volts to milliVolts
shunt_voltage_mV = shunt_voltage_V / 1000
# Convert power from Watts to milliWatts
power_mW = power_W / 1000
# Send data to computer console over USB
# Output values to 2 decimal place
print("Bus Voltage: " + "{:.2f}".format(bus_voltage_V) + " V")
print("Shunt Voltage: " + "{:.2f}".format(shunt_voltage_mV) + " mV")
print("Load Voltage: " + "{:.2f}".format(loadVoltage_V) + " V")
print("Current: " + "{:.2f}".format(current_mA) + " mA")
print("Power: " + "{:.2f}".format(power_mW) + " mW")
# Check internal calculations haven't overflowed for current
if ina219_obj.current_overflow:
print("Current Overflow Detected!")
except DeviceRangeError as e:
# Current out of device range with specified shunt resister
print(e)
print("")
# delay a second
time.sleep(1)