More Micropython programmers — and especially beginners — should know about Awesome MicroPython. It’s a community-curated list of remarkably decent MicroPython libraries, frameworks, software and resources. If you need to interface to a sensor, look there first.
For example, take the INA219 High Side DC Current Sensor. It’s an I²C sensor able to measure up to 26 V, ±3.2 A. It does this by measuring the voltage across a 0.1 ohm precision shunt resistor with its built-in 12-bit ADC. I got a customer return from the store that was cosmetically damaged but still usable, so I thought I’d try it with the simplest module I could find in Awesome MicroPython and see how well it worked.
I guess I needed a test circuit too. Using all of what was immediately handy — a resistor I found on the bench and measured at 150.2 ohm — I came up with this barely useful circuit:
The INA219 would be happier with a much higher current to measure, but I didn’t have anything handy that could do that.
Looking in Awesome MicroPython’s Current section, I found robert-hh/INA219: INA219 Micropython driver. It doesn’t have much (okay, any) documentation, but it’s a very small module and the code is easy enough to follow. I put the ina219.py module file into the /lib folder of a WeAct Studio RP2040 board, and wrote the following code:
# INA219 demo - uses https://github.com/robert-hh/INA219 from machine import Pin, I2C import ina219 i = I2C(0, scl=Pin(5), sda=Pin(4)) print("I2C Bus Scan: ", i.scan(), "\n") sensor = ina219.INA219(i) sensor.set_calibration_16V_400mA() # my test circuit is 3V3 supply through 150.2 ohm resistor r_1 = 150.2 r_s = 0.1 # shunt resistor on INA219 board # current is returned in milliamps print("Current / mA: %8.3f" % (sensor.current)) # shunt_voltage is returned in volts print("Shunt voltage / mV: %8.3f" % (sensor.shunt_voltage * 1000)) # estimate supply voltage from known resistance * sensed current print("3V3 (sensed) / mV: %8.3f" % ((r_1 + r_s) * sensor.current))
with everything wired up like this (Blue = SDA, Yellow = SCL):
Running it produced this:
I2C Bus Scan:  Current / mA: 22.100 Shunt voltage / mV: 2.210 3V3 (sensed) / mV: 3321.630
So it’s showing just over 22 mA: pretty close to what I calculated!