import machine
import time
import urequests
import network
import ujson
import dht
#thingspeak settings
THINGSPEAK_APK_KEY=""
THINGSPEAK_URL=""
#wifi settings
WIFI_SSID="wokwi-GUEST"
WIFI_PASSWORD=" "
#DHT22 (AM2302) sensor on GPIO 4
dht_sensor= dht.DHT22(machine.Pin(4))
#function to read room temperature and humidity
def read_room_temprature_humidity():
dht_sensor.measure()
temprature=dht_sensor.humidity():
return temperature, humidity
#function to send data to thingspeak
def send_data_to_thingspeak(temperature, humidity):
data={
"api_key":THINGSPEAK_API_KEY,
"field1":temperature,
"field2": humidity,
}
response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data), headers={"Content-Type": "application/json"})
response.close()
# Initialize the Wi-Fi 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:
temperature, humidity = read_room_temperature_humidity()
send_data_to_thingspeak(temperature, humidity)
print("Data sent to ThingSpeak")
time.sleep(15) # Send data every 15 seconds (adjust the interval as needed)
except KeyboardInterrupt:
passLoading
pi-pico-w
pi-pico-w