import network
import urequests
from machine import Pin
from time import sleep
# WiFi credentials
SSID = "pi8b"
PASSWORD = "1234567890"
# ThingSpeak settings
THINGSPEAK_WRITE_API_KEY = "7IPP59WL5IZFOH1E"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# Digital sound sensor input (on GP15)
sound_sensor = Pin(15, Pin.IN)
def connect_wifi(ssid, pwd):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi …")
wlan.connect(ssid, pwd)
while not wlan.isconnected():
sleep(1)
print("Connected, IP:", wlan.ifconfig())
return wlan
def read_sound_sensor():
# Returns 1 if sound detected, else 0
return sound_sensor.value()
def upload_to_thingspeak(sound_detected):
# Upload 1 or 0 to ThingSpeak field1
url = f"{THINGSPEAK_URL}?api_key={THINGSPEAK_WRITE_API_KEY}&field1={sound_detected}"
try:
response = urequests.get(url)
print("ThingSpeak response:", response.text)
response.close()
except Exception as e:
print("Failed to send data:", e)
def main_loop():
connect_wifi(SSID, PASSWORD)
while True:
sound_state = read_sound_sensor()
print("Sound detected:" if sound_state else "No sound")
upload_to_thingspeak(sound_state)
# ThingSpeak free channel limits updates to every 15 seconds
sleep(15)
if __name__ == "__main__":
main_loop()