from machine import Pin
import dht
import time
import urequests
import json
# Setup DHT22 Sensor
sensor = dht.DHT22(Pin(14))
# Google Sheets Web App URL
url = "https://script.google.com/macros/library/d/1xi5x5ARguw0lbVRgWM63mYBns6b9BeUpTnQ9me1h_tKgJlSkwqIosa8x/1" # Ganti dengan URL dari Apps Script
def read_sensor():
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
return temperature, humidity
def send_to_sheet(temp, hum):
headers = {'Content-Type': 'application/json'}
data = {
'temperature': temp,
'humidity': hum
}
try:
response = urequests.post(url, headers=headers, data=json.dumps(data))
print("Data sent, status code:", response.status_code)
print("Response:", response.text)
response.close()
except Exception as e:
print("Failed to send data:", str(e))
while True:
try:
temperature, humidity = read_sensor()
print("Temperature: {} C, Humidity: {} %".format(temperature, humidity))
send_to_sheet(temperature, humidity)
except Exception as e:
print("Error reading sensor or sending data:", str(e))
time.sleep(600) # Wait for 10 minutes