print("Hello, ESP32!")
import network
import time
import machine
from umqtt.simple import MQTTClient
# WiFi and MQTT variables
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASS = ''
MQTT_BROKER = 'test.mosquitto.org'
MQTT_TOPIC = b'odisha/microgrid/data'
MQTT_ALERT = b'odisha/microgrid/alert'
# Connect WiFi function
def wifi_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(0.5)
print('Connected to WiFi:', wlan.ifconfig())
wifi_connect()
# ADC Setup for potentiometers
pot_solar = machine.ADC(machine.Pin(32))
pot_solar.atten(machine.ADC.ATTN_11DB)
pot_battery = machine.ADC(machine.Pin(33))
pot_battery.atten(machine.ADC.ATTN_11DB)
pot_load = machine.ADC(machine.Pin(34))
pot_load.atten(machine.ADC.ATTN_11DB)
# Conversion functions
def adc_to_voltage(adc):
return round(adc * 3.3 / 4095, 2)
def adc_to_current(adc):
return round(adc * 3.3 / 4095 / 66, 3) # Simulate max 0.05A
# MQTT client setup
client = MQTTClient("esp32-microgrid", MQTT_BROKER)
client.connect()
print('Connected to MQTT Broker')
while True:
# Read ADC values
solar_adc = pot_solar.read()
battery_adc = pot_battery.read()
load_adc = pot_load.read()
# Convert ADC readings to voltage/current
solar_v = adc_to_voltage(solar_adc)
battery_v = adc_to_voltage(battery_adc)
load_a = adc_to_current(load_adc)
# Calculate solar generation and battery storage level
solar_gen = round(solar_v * load_a, 3) # simple proxy calculation
battery_lvl = battery_v
# Create JSON payload
msg = ('{"microgrid/solarVoltage": %.2f, "microgrid/batteryVoltage": %.2f, "load_current": %.3f, '
'"microgrid/powerGeneration": %.3f, "microgrid/powerTransmission": %.2f, "microgrid/powerConsumption": %.3f}' %
(solar_v, battery_v, load_a, solar_gen, battery_lvl, load_a))
# Publish sensor data
client.publish(MQTT_TOPIC, msg)
# Check and publish alert messages if thresholds crossed
if solar_v < 1.5:
client.publish(MQTT_ALERT, b'ALERT: Solar generation low!')
if battery_v > 3.2:
client.publish(MQTT_ALERT, b'ALERT: Battery full!')
if load_a < 0.05:
client.publish(MQTT_ALERT, b'ALERT: Load current low!')
# Console print for debugging
print(msg)
# Delay before next reading
time.sleep(2)