import machine
import time
import urequests
import network
import ujson
import dht
# ThingSpeak settings
THINGSPEAK_API_KEY = "2KU4MIEB0UKRKI45"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# Wi-Fi settings
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# PIR motion sensor pin
PIR_PIN = machine.Pin(14, machine.Pin.IN)
# DHT22 (AM2302) sensor on GPIO 4
dht_sensor = dht.DHT22(machine.Pin(4))
# Cleanliness sensor connected to an analog pin
CLEANLINESS_SENSOR_PIN = machine.ADC(0) # Example: Use GPIO 26 for cleanliness sensor
# Function to read data from the PIR sensor
def read_pir_sensor():
return PIR_PIN.value()
# 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 read cleanliness data
def read_cleanliness_sensor():
# Read the cleanliness sensor data (replace with your sensor code)
cleanliness_data = CLEANLINESS_SENSOR_PIN.read_u16()
return cleanliness_data
# Function to send data to ThingSpeak
def send_data_to_thingspeak(occupancy, temperature, humidity, cleanliness):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": occupancy,
"field2": temperature,
"field3": humidity,
"field4": cleanliness,
}
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:
occupancy = read_pir_sensor()
temperature, humidity = read_room_temperature_humidity()
cleanliness = read_cleanliness_sensor()
send_data_to_thingspeak(occupancy, temperature, humidity, cleanliness)
print("Data sent to ThingSpeak")
time.sleep(15) # Send data every 15 seconds (adjust the interval as needed)
except KeyboardInterrupt:
pass