print("Hello, ESP32!")
from machine import Pin, ADC
import network
import time
from umqtt.simple import MQTTClient
# -----------------
# MQTT Configuration
# -----------------
MQTT_BROKER = "broker.emqx.io" # Free public MQTT broker
MQTT_CLIENT_ID = "esp32-energy"
MQTT_TOPIC = b"esp32/energy"
# -----------------
# Wi-Fi Credentials (Wokwi Simulation)
# -----------------
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
# -----------------
# Wi-Fi Connection
# -----------------
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(0.5)
print("Connected:", wlan.ifconfig())
# -----------------
# ADC Configuration (3 potentiometers)
# -----------------
adc_solar = ADC(Pin(32)) # Solar Voltage
adc_battery = ADC(Pin(33)) # Battery Voltage
adc_current = ADC(Pin(34)) # Current
# Full 0–3.3V range
for adc in [adc_solar, adc_battery, adc_current]:
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)
# -----------------
# MQTT Setup
# -----------------
def connect_mqtt():
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.connect()
print("Connected to MQTT broker")
return client
# -----------------
# Main Program Loop
# -----------------
def main():
connect_wifi()
client = connect_mqtt()
while True:
# Read sensor values
solar_v = adc_solar.read() * (3.3 / 4095)
battery_v = adc_battery.read() * (3.3 / 4095)
current_a = adc_current.read() * (3.3 / 4095) # assume 0–3.3V → 0–3.3A
power_w = solar_v * current_a
# Create data packet
data = {
"solar_voltage": round(solar_v, 2),
"battery_voltage": round(battery_v, 2),
"current": round(current_a, 2),
"power": round(power_w, 2)
}
# Publish to MQTT
msg = str(data)
client.publish(MQTT_TOPIC, msg)
print("Published:", msg)
time.sleep(2) # update interval
# -----------------
# Run Main
# -----------------
if __name__ == "__main__":
main()