import machine, dht, time
import network
import urequests
# Connect to Wi-Fi (Wokwi simulation only supports Wokwi-GUEST)
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
# Wait until connected
while not wifi.isconnected():
print("Reconnecting...")
time.sleep(1)
print("Connected:", wifi.ifconfig())
# DHT22 temperature and humidity sensor on GPIO4
sensor = dht.DHT22(machine.Pin(4))
# LDR (light sensor) on GPIO34 as ADC input
ldr = machine.ADC(machine.Pin(34))
ldr.atten(machine.ADC.ATTN_11DB) # Full voltage range 0-3.3V
# LEDs on GPIO 26, 27, 14, 12 as output pins
led1 = machine.Pin(26, machine.Pin.OUT)
led2 = machine.Pin(27, machine.Pin.OUT)
led3 = machine.Pin(14, machine.Pin.OUT)
led4 = machine.Pin(12, machine.Pin.OUT)
# Servo motor on GPIO18 for cooling fan simulation
servo = machine.PWM(machine.Pin(18), freq=50)
# Update this URL each time you restart app.py
FLASK_URL = "http://duplicate-islamist-appraisal.ngrok-free.dev/update"
while True:
sensor.measure() # Read DHT22 sensor
temp = sensor.temperature() # Get temperature in °C
hum = sensor.humidity() # Get humidity in %
light_val = ldr.read() # Get raw ADC value (0-4095)
light_lux = round((light_val / 4095) * 1000) # Convert to 0-1000 lux scale
print("Temp:", temp, "°C Hum:", hum, "% Light:", light_lux, "lux")
# Turn LEDs on when dark (below 450 lux)
# Note: threshold is 450 because Wokwi LDR has a built-in offset
# that prevents readings from dropping below ~450 even at minimum illumination
if light_lux < 450:
led1.on(); led2.on(); led3.on(); led4.on() # All LEDs on
else:
led1.off(); led2.off(); led3.off(); led4.off() # All LEDs off
# Spin servo (simulate cooling fan) when temp is >= 35°C
if temp >= 35:
servo.duty(115) # Fan on (full rotation)
else:
servo.duty(40) # Fan off (rest position)
# Send sensor data to Flask server
try:
response = urequests.post(
FLASK_URL,
json={"temperature": temp, "humidity": hum, "light": light_lux},
headers={"ngrok-skip-browser-warning": "true"} # Bypass ngrok browser warning
)
print("Server response:", response.status_code)
response.close() # Free memory after response
except Exception as e:
print("Failure to send data:", e)
time.sleep(2) # Wait 2 seconds before next reading