#include <SoftwareSerial.h>
import machine
import network
import time
import urequests
import ujson
import dht
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# ThingSpeak API settings
THINGSPEAK_API_KEY = "TCD7Y8DBY9VYXHBR"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# LDR sensor connected to an analog pin (use GPIO pin supported for ADC)
LDR_SENSOR_PIN = machine.ADC(1) # Replace with the correct pin for LDR in your setup
# DHT22 (AM2302) sensor on GPIO 4
dht_sensor = dht.DHT22(machine.Pin(4))
# Function to read analog data from the LDR sensor
def read_ldr():
ldr_data = LDR_SENSOR_PIN.read_u16() # Reads the LDR sensor data
return ldr_data
# Function to calculate lux from ADC value
def cal_lux(ADC):
vout = ADC / 65535 * 5
RLDR = 2000 * vout / (1 - vout / 5)
lux = pow(50 * 1000 * pow(10, 0.7) / RLDR, (1 / 0.7))
return lux
# Function to read room temperature and humidity
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 with progress messages
def send_data_to_thingspeak(LUX, TEMP, HUMID):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": LUX,
"field2": TEMP,
"field3": HUMID,
}
print("Preparing data to send...")
try:
print("Connecting to ThingSpeak...")
response = urequests.post(
THINGSPEAK_URL, data=ujson.dumps(data), headers={"Content-Type": "application/json"}
)
print("Data sent successfully!")
print(f"ThingSpeak Response: {response.text}")
response.close()
except Exception as e:
print(f"Error sending data: {e}")
# Initialize the Wi-Fi connection
def connect_to_wifi():
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to Wi-Fi...")
while not wifi.isconnected():
time.sleep(1)
print("Connected to Wi-Fi")
# Main execution loop
def main():
connect_to_wifi()
while True:
try:
print("Reading sensors...")
ADC = read_ldr()
LUX = cal_lux(ADC)
TEMP, HUMID = read_room_temperature_humidity()
print(f"LUX: {LUX:.2f}, TEMP: {TEMP:.2f}°C, HUMID: {HUMID:.2f}%")
# Progress of sending data
print("Sending data to ThingSpeak...")
send_data_to_thingspeak(LUX, TEMP, HUMID)
print("Waiting before next update...")
except Exception as e:
print(f"Error: {e}")
time.sleep(10) # Adjust the delay as needed
# Run the main loop
main()