from machine import Pin, ADC, SoftI2C,
import time
from i2c_lcd import I2cLcd
# Constants
VOLTAGE = 230 # Voltage in volts
COST_PER_KWH = 4.0 # Cost per kWh
SENSITIVITY = 0.066 # ACS712 5A sensitivity
# Initialize ACS712 (Potentiometer) on ADC pin (GPIO 34)
acs712 = ADC(Pin(34))
acs712.width(ADC.WIDTH_12BIT) # Set resolution to 12 bits
acs712.atten(ADC.ATTN_11DB) # Full range (3.3V)
# Initialize I2C LCD
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16) # 16x2 LCD
# Variables to track energy and cost
energy, cost = 0.0, 0.0
start_time = time.time()
# Function to calculate current from ACS712
def get_current():
adc_value = acs712.read()
voltage = (adc_value / 4095.0) * 3.3
current = (voltage - 1.65) / SENSITIVITY
return abs(current)
# Function to calculate cost based on energy
def calculate_cost(energy):
return (energy / 1000) * COST_PER_KWH
while True:
current = get_current() # Read current from ACS712
power = VOLTAGE * current # Power in watts
elapsed_time = (time.time() - start_time) / 3600 # Time in hours
energy += power * elapsed_time # Accumulate energy
# Update the total cost based on energy
cost = calculate_cost(energy)
# Display energy and cost on LCD
lcd.clear()
lcd.putstr(f"Energy: {energy:.2f}Wh\nCost: Rs {cost:.2f}")
# Reset start time and delay for 5 seconds
start_time = time.time()
time.sleep(5)