# https://wokwi.com/projects/422815041366150145
from utime import sleep_ms, ticks_ms
from machine import I2C, Pin
from i2c_lcd import I2cLcd
from ina219 import INA219, DeviceRangeError
import sys
if(sys.platform=="esp32"):
I2C_SDA =21 # GPIO21(I2C SDA)
I2C_SCL =22 # GPIO22(I2C SCL)
# I2C configuration
i2c = I2C(0, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=100000) # Reduced frequency for greater stability.
elif(sys.platform=="rp2"):
I2C_SDA =16 # GPIO16(I2C SDA)
I2C_SCL =17 # GPIO17(I2C SCL)
# I2C configuration
i2c = I2C(0, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=100000) # Reduced frequency for greater stability.
# LCD configuration
LCD_I2C_ADDR = 0x27
LCD_ROWS = 4
LCD_COLS = 20
lcd = None
# INA219 configuration
SHUNT_OHMS = 0.1
ina = None
def setup():
global lcd, ina
try:
# Initialize LCD
lcd = I2cLcd(i2c, LCD_I2C_ADDR, LCD_ROWS, LCD_COLS)
lcd.backlight_on()
lcd.clear()
# Initialize INA219
ina = INA219(SHUNT_OHMS, i2c)
ina.configure() # Uses the library's default configuration.
print("Initialized devices")
lcd.putstr("System OK")
sleep_ms(1000)
except Exception as e:
print("Setup error:", str(e))
if lcd:
lcd.clear()
lcd.putstr("Setup error")
while True:
sleep_ms(100)
def measure_and_display():
try:
voltage = ina.voltage()
current = ina.current()
power = ina.power()
sleep_ms(10) # slight delay for debounce
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("AMPEREMETER")
lcd.move_to(0, 1)
lcd.putstr(f"I:{current:6.1f}A")
lcd.move_to(0, 2)
lcd.putstr("VOLTIMETER")
lcd.move_to(0, 3)
lcd.putstr(f"V:{voltage:6.2f}V")
# Debug no console
print("=" * 30)
print(f"Voltage: {voltage:.3f} V")
print(f"Current: {current:.1f} A")
print(f"Power: {power:.1f} W")
print("=" * 30)
print("")
except DeviceRangeError:
print("Error: Voltage out of range")
lcd.clear()
lcd.putstr("Range Error")
except Exception as e:
print("Erro:", str(e))
lcd.clear()
lcd.putstr("Reading Error")
if __name__ == "__main__":
setup()
last_measure = 0
interval = 1000 # 1 second between measurements
while True:
current_time = ticks_ms()
if current_time - last_measure >= interval:
measure_and_display()
last_measure = current_time
sleep_ms(100)