import machine
import time
import urequests
import network
import ujson
# ThingSpeak settings
THINGSPEAK_API_KEY = "JBSGA2DZAT7M9524"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# Wi-Fi settings
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# PIR sensor on GPIO 4
pir_sensor = machine.Pin(4, machine.Pin.IN)
# Function to read the PIR state
def read_pir_state():
return pir_sensor.value()
# Function to send data to ThingSpeak
def send_data_to_thingspeak(motion_detected):
data = {
"api_key": THINGSPEAK_API_KEY,
"field1": motion_detected,
}
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:
print("Monitoring motion...")
while True:
motion_detected = read_pir_state()
if motion_detected:
print("Motion detected!")
send_data_to_thingspeak(1)
else:
print("No motion.")
send_data_to_thingspeak(0)
time.sleep(3) # Check for motion every 3 seconds
except KeyboardInterrupt:
print("Program stopped by user")