import network
import time
import ntptime
import urequests
from machine import Pin
import dht
# ===============================
# WIFI & SERVER
# ===============================
ssid = 'Wokwi-GUEST'
password = ''
server_url = 'https://script.google.com/macros/s/AKfycbzRc2xrPa0owl8JBQtEdfX37VeCFL_RbmDrSzfECGYtjkIO2P1HunqKyy7pItsNA4MVdQ/exec'
ntptime.host = 'pool.ntp.org'
DEVICE_NAME = "ESP32-Gudang"
# ===============================
# SENSOR SETUP
# ===============================
dht_sensor = dht.DHT22(Pin(14))
pir_sensor = Pin(13, Pin.IN)
# ===============================
# WIFI CONNECT
# ===============================
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
print("Connecting WiFi...")
time.sleep(1)
print("WiFi Connected:", wlan.ifconfig())
# ===============================
# TIME
# ===============================
def get_ntp_time():
try:
ntptime.settime()
tm = time.localtime()
return "%04d-%02d-%02d %02d:%02d:%02d" % tm[0:6]
except:
return "1970-01-01 00:00:00"
# ===============================
# SEND DATA
# ===============================
def send_data(motion, suhu):
waktu = get_ntp_time()
print("📤 Send →", suhu, "°C | Motion:", motion)
payload = {
"method": "append",
"waktu": waktu,
"motion": motion,
"suhu": suhu,
"device": DEVICE_NAME
}
try:
r = urequests.post(server_url, json=payload)
r.close()
except Exception as e:
print("HTTP Error:", e)
# ===============================
# MAIN LOGIC (STATE MACHINE)
# ===============================
connect_wifi()
print("🚀 SYSTEM READY")
last_motion = 0
last_send = 0
SEND_INTERVAL = 10 # seconds
while True:
now = time.time()
motion = pir_sensor.value()
# Read temperature
try:
dht_sensor.measure()
suhu = dht_sensor.temperature()
except:
suhu = None
# ---- PERIODIC TEMP SEND ----
if now - last_send >= SEND_INTERVAL and suhu is not None:
send_data(False, suhu)
last_send = now
# ---- MOTION EDGE DETECTION ----
if motion == 1 and last_motion == 0 and suhu is not None:
print("🚨 MOTION DETECTED!")
send_data(True, suhu)
last_motion = motion
time.sleep(0.2)