import time
import urequests
import dht
from machine import Pin, PWM
# Wi-Fi settings
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# ThingSpeak settings
THING_SPEAK_API_KEY = "2308799"
THING_SPEAK_URL = "https://api.thingspeak.com/update"
THING_SPEAK_API_KEY = "Y5D386LU3W5X66Y2"
THING_SPEAK_FIELD1 = "field1"
THING_SPEAK_FIELD2 = "field2"
# LED pins
LED1_PIN = 21 # Replace with the GPIO pin connected to LED1
LED2_PIN = 22 # Replace with the GPIO pin connected to LED2
LED1 = PWM(Pin(LED1_PIN), freq=1000, duty=0)
LED2 = PWM(Pin(LED2_PIN), freq=1000, duty=0)
# DHT sensor settings
DHT_PIN = 2 # Replace with the GPIO pin connected to the DHT22 sensor
dht_sensor = dht.DHT22(Pin(DHT_PIN))
def connect_to_wifi():
import network
wlan = network.WLAN(network.STA_IF)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
pass
print("Connected to WiFi")
def read_sensor_data():
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
return temperature, humidity
def publish_to_thingspeak(temperature, humidity):
url = "{}?{}={:.2f}&{}={:.2f}&api_key={}".format(
THING_SPEAK_URL,
THING_SPEAK_FIELD1, temperature,
THING_SPEAK_FIELD2, humidity,
THING_SPEAK_API_KEY
)
print("Sending data to ThingSpeak:", url) # Debug line
response = urequests.get(url)
print("ThingSpeak response:", response.text) # Debug line
response.close()
def control_leds(temperature, humidity):
if temperature > 25.0 and humidity > 70.0:
print("Air quality might be poor (high temperature and humidity).")
LED1.duty(1023) # Full brightness for LED1
LED2.duty(0) # LED2 off
elif temperature < 20.0 and humidity < 30.0:
print("Air quality might be poor (low temperature and humidity).")
LED1.duty(0) # LED1 off
LED2.duty(1023) # Full brightness for LED2
else:
print("Air quality appears to be normal.")
LED1.duty(0) # LED1 off
LED2.duty(0) # LED2 off
def main():
connect_to_wifi()
while True:
temperature, humidity = read_sensor_data()
print("Temperature: {:.2f}°C".format(temperature))
print("Humidity: {:.2f}%".format(humidity))
publish_to_thingspeak(temperature, humidity)
control_leds(temperature, humidity)
time.sleep(15) # Delay for the next measurement (15 seconds)
if __name__ == "__main__":
main()