import network
import urequests
from machine import ADC,Pin
import time
import dht
import math
# Replace with your Wi-Fi network credentials
# Replace with your ThingSpeak API key and channel ID
API_KEY = '7X4NETQTTUDE93YS'
CHANNEL_ID = '2104032'
# Define the GPIO pin connected to the DHT22 sensor
sensor = dht.DHT22(Pin(14))
ldr_pin = 2
gama = 0.7
rl10 = 50
def map(value, fromLow, fromHigh, toLow, toHigh):
return int((value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow)
ldr_pin = Pin(2, Pin.IN)
#adc = LDR(Pin(2))
#adc.atten(ADC.ATTN_11DB)
def ldr():
nilaiLDR = adc.measure()
nilaiLDR = map(nilaiLDR, 4095, 0, 1024, 0) # Mengubah nilai pembacaan sensor LDR dari nilai ADC Arduino menjadi nilai ADC ESP32
voltase = nilaiLDR / 1024. * 5
resistansi = 2000 * voltase / (1 - voltase / 5)
kecerahan = pow(rl10 * 1e3 * pow(10, gama) / resistansi, (1 / gama))
print("Kecerahan =", kecerahan)
return kecerahan
# Connect to Wi-Fi network
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Main loop
while True:
try:
time.sleep(2)
ldr_value = ldr_pin.value()
print("LDR value:", ldr_value)
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
url = 'https://api.thingspeak.com/update?api_key=' + API_KEY + '&field1=' + str(hum) +'&field2=' + str(temp)
response = urequests.get(url)
print('Data sent to ThingSpeak:', response.text)
response.close()
temp_f = temp * (9/5) + 32.0
print('Temperature: %3.1f C' %temp)
print('Temperature: %3.1f F' %temp_f)
print('Humidity: %3.1f %%' %hum)
except OSError as e:
print('Failed to read sensor.')