from machine import Pin, PWM, ADC
import dht
import time
import network
import urequests
# =========================
# WIFI
# =========================
def connect_wifi():
print("Menghubungkan ke WiFi", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('Wokwi-GUEST', '') # SSID khusus simulasi Wokwi
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("\nWiFi Terhubung!")
connect_wifi()
# =========================
# BLYNK
# =========================
BLYNK_TOKEN = "wxbwqNiMTznb6m7H-wiIHWdoQEAWe0Og"
BLYNK_URL = "https://blynk.cloud/external/api/update"
# =========================
# PIN SETUP
# =========================
led_ldr = Pin(14, Pin.OUT)
relay = Pin(4, Pin.OUT)
ldr = ADC(Pin(27))
ldr.atten(ADC.ATTN_11DB)
sensor = dht.DHT22(Pin(15))
buzzer = PWM(Pin(5), freq=1000, duty=0)
# =========================
# PARAMETER
# =========================
threshold_ldr = 2000
batas_suhu = 35
# =========================
# LOOP
# =========================
while True:
try:
# ===== PIR =====
motion = pir.value()
led_pir.value(motion)
# ===== LDR =====
nilai_ldr = ldr.read()
if nilai_ldr < threshold_ldr:
led_ldr.value(1)
else:
led_ldr.value(0)
# ===== DHT22 =====
sensor.measure()
suhu = sensor.temperature()
hum = sensor.humidity()
print("Suhu:", suhu, "LDR:", nilai_ldr, "PIR:", motion)
# ===== LOGIKA SUHU =====
if suhu > batas_suhu:
relay.value(1)
buzzer.duty(512)
else:
relay.value(0)
buzzer.duty(0)
# =========================
# KIRIM KE BLYNK
# =========================
url = BLYNK_URL + "?token=" + BLYNK_TOKEN \
+ "&V0=" + str(suhu) \
+ "&V1=" + str(hum) \
+ "&V2=" + str(nilai_ldr) \
+ "&V3=" + str(motion)
r = urequests.get(url)
r.close()
except Exception as e:
print("Error:", e)
time.sleep(2)