import machine
import network
import time
import urequests
import ujson
import dht
from dht import DHT22
#WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
#Thingspeak API settings
THINGSPEAK_API_KEY = "Q4EY237OOZAHML86"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# DHT22 (AM2302) SENSOR ON GPIO 4
dht_sensor = dht.DHT22 (machine.Pin(4))
#ldr sensor connected to an analog pin
LDR_SENSOR_PIN = machine.ADC(1)
# 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 interpret condition
def interpret_conditions(lux, temperature, humidity):
lux_condition = "Bright" if lux > 600 else "Dark" # Adjust the threshold as needed
temp_condition = "Hot" if temperature > 27 else "Cold"
humidity_condition = "Wet" if humidity > 60 else "Dry"
print(f"Lux Condition: {lux_condition}\nTemp Condition: {temp_condition}\nHumidity Condition: {humidity_condition}")
if lux_condition == "Bright" and humidity_condition == "Dry" and temp_condition == "Cold":
print("The room is suitable for reading")
else:
print("The room is not suitable for reading")
#Function for light intensity conversion
def read_ldr():
GAMMA = 0.7
RL10 = 50
ldr_data = LDR_SENSOR_PIN.read_u16()
voltage = ldr_data / 65535 * 5
# Check for zero voltage to avoid division by zero
if voltage == 5.0:
return float('inf') # Return infinity as a placeholder for undefined lux value
resistance = 2000 * voltage / (1 - voltage / 5)
lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA))
return lux
# Function to send data to Thingspeak
def send_data_to_thingspeak(lux, temperature, humidity):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": lux,
"field2": temperature,
"field3": humidity,
}
response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data), headers={"Content-Type": "application/json"})
response.close()
#Initialize the wi-Fi connection
print("Connecting to WiFi", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print(wlan.ifconfig())
if __name__ == "__main__":
try:
while True:
lux = read_ldr()
temperature, humidity = read_room_temperature_humidity()
print(f"lux: {lux}")
print(f"Temp: {temperature}")
print(f"Hum: {humidity}")
interpret_conditions(lux, temperature, humidity) # Call interpret_conditions
send_data_to_thingspeak(lux, temperature, humidity) # Pass both temperature and humidity
print("Data sent to Thingspeak")
time.sleep(10)
except KeyboardInterrupt:
pass