import machine
import network
import time
import urequests
import ujson
import dht
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# ThingSpeak credentials
THINGSPEAK_API_KEY = "GPRJQ9GXHZTCP5H1"
THINGSPEAK_URL = "https://api.thingspeak.com/update"
# DHT22 (AM2302) sensor on analog pin
dht_sensor = dht.DHT22(machine.Pin(4))
# LDR sensor on GPIO 27
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
RL10 = 50
voltage = ldr / 65535 * 5
resistance = 2000 * voltage / (1 - voltage / 5)
lux_value = (RL10 * 1e3 * pow(10, GAMMA) / resistance) ** (1 / GAMMA)
return lux_value
def read_room_temperature_humidity():
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
return temperature, humidity
# Function to send data to ThingSpeak
def send_data_to_thingspeak(ldr, temperature, humidity):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": ,
"field2": ,
"field3": ,
}
response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data),headers={"Content-Type":"application/json"})
response.close()
# Initialize tthe 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:{ldr}")
lux = adc_to_lux()
print(f"Lux Value: {lux}")
temperature, humidity = read_room_temperature_humidity()
print(f"Temp:{temperature}")
print(f"Hum:{humidity}")
send_data_to_thingspeak(ldr, temperature, humidity)
print("Data sent to ThingSpeak")
time.sleep(15) # Send data every 15 seconds (adjust the interval as needed)
except KeyboardInterrupt:
pass