import machine
import network
import time
import urequests
import ujson
import utime
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# ThingSpeak credentials
THINGSPEAK_API_KEY = "V1DLGOM7Z9FE7W9M"
THINGSPEAK_URL = "https://api.thingspeak.com/update"
# DHT22 (AM2302) sensor on GPIO 4
LDR_SENSOR_PIN = machine.ADC(1)
# Function to read analog pin
def read_ldr():
ldr_data = LDR_SENSOR_PIN.read_u16()
return ldr_data
def adc_to_lux():
GAMMA = 0.7
RL = 50
voltage = ldr / 65535 * 5
resistance = 2000 * voltage / (1 - voltage / 5)
lux_value = (RL * 1e3 * pow(10, GAMMA) / resistance) ** (1 / GAMMA)
return lux_value
# Function to send data to ThingSpeak
def send_data_to_thingspeak(ldr, lux):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": ldr,
"field2": lux,
}
response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data),headers={"Content-Type":"application/json"})
response.close()
# Initialize the Wifi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID,WIFI_PASSWORD)
# wait for the Wi-Fi connection to establish
while not wifi.isconnected():
time.sleep(1)
print("Connected to Wi-Fi")
if __name__ == "__main__":
try:
while True:
ldr = read_ldr()
print(f"ADC:{ldr}")
lux = adc_to_lux()
print(f"Lux Value: {lux}")
send_data_to_thingspeak(ldr, lux)
print("Data sent to ThingSpeak")
time.sleep(30)
except KeyboardInterrupt:
pass