import network
import urequests
import dht
from machine import Pin
from time import sleep
import ntptime
import time
import random
# ===============================
# MODE SELECT
# ===============================
SIMULATION = True # True = fake data | False = real DHT22
# ===============================
# REAL DHT22 SETUP
# ===============================
dht_pin = Pin(4)
dht_sensor = dht.DHT22(dht_pin)
# ===============================
# SIMULATED DHT22 VALUES
# ===============================
temperature = 28.0
humidity = 60.0
def fake_dht_read():
global temperature, humidity
temperature += random.uniform(-0.3, 0.3)
humidity += random.uniform(-1.0, 1.0)
temperature = max(20.0, min(40.0, temperature))
humidity = max(30.0, min(90.0, humidity))
return round(temperature, 1), round(humidity, 1)
# ===============================
# WIFI & SERVER
# ===============================
ssid = 'Wokwi-GUEST'
password = ''
server_url = 'https://script.google.com/macros/s/AKfycbxtylAAwhAMI0JLGR-3wsW8cmrDrTkC5rJOriq8DKiePqbLWRZXAUBRR1vA3hTXHYJ0sA/exec'
ntptime.host = 'pool.ntp.org'
# ===============================
# CONNECT WIFI
# ===============================
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
print("Connecting to WiFi...")
sleep(1)
print("Connected:", wlan.ifconfig())
# ===============================
# GET TIME
# ===============================
def get_ntp_time():
try:
ntptime.settime()
tm = time.localtime()
return "{:02d}:{:02d}:{:02d}".format(tm[3], tm[4], tm[5])
except:
return "00:00:00"
# ===============================
# SEND DATA
# ===============================
def send_data():
if SIMULATION:
temperature, humidity = fake_dht_read()
else:
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
except OSError as e:
print("DHT Error:", e)
return
timestamp = get_ntp_time()
print("Sending →", temperature, "°C", humidity, "%", timestamp)
json_data = {
"method": "append",
"temperature": temperature,
"humidity": humidity,
"timestamp": timestamp
}
try:
response = urequests.post(server_url, json=json_data)
print("Response:", response.status_code)
response.close()
except Exception as e:
print("Error:", e)
# ===============================
# MAIN LOOP
# ===============================
def main_loop():
while True:
send_data()
sleep(5) # ⏱ send interval
# ===============================
# START
# ===============================
connect_wifi()
main_loop()