import network
import urequests
import time
from machine import Pin
import dht
# Konfigurasi WiFi
SSID = "Wokwi-GUEST"
PASSWORD = ""
# Token Ubidots & API URL
UBIDOTS_TOKEN = "UBIDOTS_TOKEN_ANDA" # Ganti dengan token API dari Ubidots
DEVICE_LABEL = "esp32-sensor" # Ganti dengan label perangkat di Ubidots
UBIDOTS_URL = f"https://industrial.api.ubidots.com/api/v1.6/devices/{DEVICE_LABEL}/"
# Inisialisasi Sensor
PIR = Pin(2, Pin.IN) # Sensor PIR di GPIO14
DHT = dht.DHT22(Pin(15)) # Sensor DHT22 di GPIO12
# Fungsi untuk koneksi WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Menghubungkan ke WiFi...")
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(1)
print("Terhubung ke WiFi! IP Address:", wlan.ifconfig()[0])
# Fungsi untuk mengirim data ke Ubidots menggunakan REST API
def send_to_ubidots(temperature, humidity, motion):
headers = {
"X-Auth-Token": UBIDOTS_TOKEN,
"Content-Type": "application/json"
}
data = {
"temperature": temperature,
"humidity": humidity,
"motion": motion
}
try:
response = urequests.post(UBIDOTS_URL, json=data, headers=headers)
print("Data dikirim ke Ubidots:", response.text)
response.close()
except Exception as e:
print("Gagal mengirim data:", e)
# Loop utama
def main():
connect_wifi()
while True:
try:
# Baca sensor DHT22
DHT.measure()
temperature = DHT.temperature()
humidity = DHT.humidity()
except Exception as e:
print("Error membaca sensor DHT22:", e)
temperature = None
humidity = None
# Baca sensor PIR
motion = PIR.value() # 0 = tidak ada gerakan, 1 = ada gerakan
print(f"Suhu: {temperature}°C | Kelembaban: {humidity}% | Gerakan: {motion}")
# Kirim data ke Ubidots
if temperature is not None and humidity is not None:
send_to_ubidots(temperature, humidity, motion)
else:
print("Data sensor tidak valid, pengiriman dibatalkan.")
time.sleep(10) # Jeda 10 detik sebelum pengiriman berikutnya
# Jalankan program
if __name__ == "__main__":
main()