import network
import json
import dht
import time
from machine import Pin, ADC
from umqtt.simple import MQTTClient
# consts
RELAY_PIN_NUMBER = 22
LDR_PIN_NUMBER = 32
LUX_THRESHOLD = 500
GAMMA = 0.7
RL10 = 33
SSID, PASS = "Wokwi-GUEST", ""
BROKER = "broker.emqx.io"
TOPIC = b"pucpr/iot"
# setup
relay = Pin(RELAY_PIN_NUMBER, Pin.OUT)
photoresistor = ADC(Pin(LDR_PIN_NUMBER))
w = network.WLAN(network.STA_IF); w.active(True)
w.connect(SSID, PASS)
while not w.isconnected():
time.sleep(0.1)
cid = b"esp32-" + str(int(time.time()*1000)).encode()
c = MQTTClient(cid, BROKER)
c.connect()
def ldr_to_lux():
analog_value = photoresistor.read()
voltage = analog_value / 4096. * 3.3;
resistance = 2000 * voltage / (1 - voltage / 3.3);
lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
return lux
def main():
print("Starting the Lighting Automation Circuit...")
while True:
try:
luminosity = ldr_to_lux()
if luminosity <= LUX_THRESHOLD:
relay.value(1)
led_status = "ON"
else:
relay.value(0)
led_status = "OFF"
payload = {
"luminosity_lux": round(luminosity, 2),
"light_status": led_status
}
c.publish(TOPIC, json.dumps(payload))
print(f"PUB -> {payload}")
except OSError as e:
print("Hardware or network operation failure:", e)
time.sleep(2)
if __name__ == "__main__":
main()