Skip to content

Instantly share code, notes, and snippets.

@ciniml
Created June 7, 2021 20:32
Show Gist options
  • Save ciniml/2c6c6d703f8129ca7df50e262af26fde to your computer and use it in GitHub Desktop.
Save ciniml/2c6c6d703f8129ca7df50e262af26fde to your computer and use it in GitHub Desktop.
Measure voltage, current and power with Circuit Python on RPi Pico
from board import *
from busio import I2C
import struct
import time
i2c = I2C(GP21, GP20)
i2c.try_lock()
vm_address = 0x49
cm_address = 0x48
# Configure current meter
i2c.writeto(cm_address, bytes([1, 0x8e, 0xe3])) # Start Conversion, Mux(0), PGA(0.256), Mode(Cont), DR(860), No Comp
# Configure voltage meter
i2c.writeto(vm_address, bytes([1, 0x88, 0xe3])) # Start Conversion, Mux(0), PGA(0.512), Mode(Cont), DR(860), No Comp
buffer = bytearray(4)
while True:
sampling_rate = 860
sum_voltage = 0
sum_current = 0
sum_power = 0
for i in range(sampling_rate):
voltage = None
current = None
while voltage is None or current is None:
if voltage is None:
i2c.writeto_then_readfrom(vm_address, bytes([0]), buffer)
if (buffer[2] & 0x80) == 0x80:
voltage = struct.unpack(">hh", buffer)[0] * -32 / 32768.0
if current is None:
i2c.writeto_then_readfrom(cm_address, bytes([0]), buffer)
if (buffer[2] & 0x80) == 0x80:
current = struct.unpack(">hh", buffer)[0] * -0.512 / 32768.0 / 0.05
sum_voltage += voltage
sum_current += current
sum_power += voltage * current
print(sum_voltage/sampling_rate, sum_current/sampling_rate, sum_power/sampling_rate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment