import network
import urequests
import time
from machine import Pin, PWM
# --- 1. CONFIGURATION ---
WIFI_SSID = "zaini"
WIFI_PASS = "1234567890"
API_KEY = "YEA4DC3HVUO2DVR3"
URL = "http://api.thingspeak.com/update"
# --- 2. HARDWARE SETUP ---
pir = Pin(16, Pin.IN)
buzzer = PWM(Pin(15))
# Setup 7-segment pins (GPIO 0 to 6)
seg_pins = [Pin(i, Pin.OUT) for i in range(7)]
# Character Map for Common Cathode (1 = ON, 0 = OFF)
# If your display is Common Anode, the 'not segments[i]' in display_char handles it.
digits = {
'H': [0, 1, 1, 0, 1, 1, 1],
'L': [0, 0, 0, 1, 1, 1, 0]
}
# --- 3. FUNCTIONS ---
def display_char(char):
segments = digits.get(char, [0,0,0,0,0,0,0])
for i in range(7):
# Using 'not' assumes Common Anode; remove 'not' if Common Cathode
seg_pins[i].value(not segments[i])
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
print("Connecting to WiFi...", end="")
# Wait for connection with a 10-second timeout
timeout = 10
while not wlan.isconnected() and timeout > 0:
time.sleep(1)
print(".", end="")
timeout -= 1
if wlan.isconnected():
print("\nConnected! IP:", wlan.ifconfig()[0])
else:
print("\nWiFi Connection Failed. Running offline mode.")
def send_to_thingspeak(val):
try:
# Construct the URL with the motion value (0 or 1)
request_url = f"{URL}?api_key={API_KEY}&field1={val}"
response = urequests.get(request_url)
print(f"Cloud Sync: {response.status_code}")
response.close()
except Exception as e:
print(f"Cloud Sync Error: {e}")
# --- 4. INITIALIZATION ---
print("System Initializing...")
buzzer.duty_u16(0)
display_char('L')
connect_wifi()
# Define last_update BEFORE the loop to prevent NameError
last_update = time.time()
print("System Active")
# --- 5. MAIN LOOP ---
while True:
motion_detected = pir.value()
if motion_detected == 1:
print("Motion!")
display_char('H')
buzzer.freq(1000)
buzzer.duty_u16(32768) # 50% duty cycle
else:
display_char('L')
buzzer.duty_u16(0)
# Update ThingSpeak every 20 seconds
if (time.time() - last_update) >= 20:
# Briefly pause buzzer so network request doesn't cause audio glitching
temp_duty = buzzer.duty_u16()
buzzer.duty_u16(0)
send_to_thingspeak(motion_detected)
last_update = time.time() # Reset the timer
buzzer.duty_u16(temp_duty) # Restore buzzer state
time.sleep(0.1)Loading
pi-pico-w
pi-pico-w