import machine
import network
import time
import urequests
import ujson
import dht
# WiFi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
#ThingSpeak APT settings
THINGSPEAK_API_KEY = "DJQQMMIDJ3OBMFU6"
THINGSPEAK_URL = "https://api.thingspeak.com/update"
# DHT22 (AM2302) sensor on GRIO 22
dht_sensor = dht.DHT22(machine.Pin(22))
# PIR sensor in Place A on GPIO 21
pir_sensor_pinA = machine.Pin(21, machine.Pin.IN)
# PIR sensor in Place B on GPIO 20
pir_sensor_pinB = machine.Pin(20, machine.Pin.IN)
# PIR sensor in Place C on GPIO 19
pir_sensor_pinC = machine.Pin(19, machine.Pin.IN)
# Connect potentiometer to ADC pin (Microphone)
sound_pin = machine.ADC(0)
# Connect potentiometer to ADC pin (Camera)
camera_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 read PIR sensor state
def read_pir():
pir_state_A = pir_sensor_pinA.value()
pir_state_B = pir_sensor_pinB.value()
pir_state_C = pir_sensor_pinC.value()
return pir_state_A, pir_state_B, pir_state_C
# Function to send data to ThingSpeak
def send_data_to_thingspeak(temperature,pir_state_A, pir_state_B, pir_state_C,sound_value,camera_value):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": temperature,
"field2": pir_state_A,
"field3": pir_state_B,
"field4": pir_state_C,
"field5": sound_value,
"field6": camera_value,
}
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()
print(f"Temp:{temperature}")
time.sleep(1)
pir_state_A, pir_state_B, pir_state_C = read_pir()
print(f"Motion Status - Place A: {pir_state_A}, Place B: {pir_state_B}, Place C: {pir_state_C}")
sound_value = sound_pin.read_u16()/ 65535 * 120
print(f"Sound Volume:{sound_value}dB")
camera_value = round(camera_pin.read_u16()/ 65535 * 1000)
print(f"Total Attendees:{camera_value}")
send_data_to_thingspeak(temperature,pir_state_A, pir_state_B, pir_state_C,sound_value,camera_value)
print("Data sent to ThingSpeak")
time.sleep(15)
except KeyboardInterrupt:
pass
Place A
Place B
Place C
Microphone
Camera