Skip to content

STEMAIDE AFRICA

Project 1.8.6: Wi-Fi PIR Motion Alert

Beginner Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython

Overview

Build a Wi-Fi motion alert page using a PIR sensor and the Pico 2 W.

This project demonstrates motion sensing, event counting, and live browser status updates.

The final result should show whether motion was recently detected and how many motion events have happened since the code started.

Required Components

Pico 2 W
Raspberry Pi Pico 2 W
PIR Sensor
PIR Motion Sensor
Breadboard
Breadboard
Jumper Wires
Jumper Wires
2.4 GHz Wi-Fi Network Phone or Computer Browser

Circuit Connections

Component Pin Connects To Pico GPIO / Physical Pin Number Notes
PIR VCC 3.3V or module-safe supply Physical Pin 36 Start with 3.3V if supported
PIR GND GND Physical Pin 38 Common ground
PIR OUT GPIO 1 GPIO 1 / Physical Pin 2 Must be 3.3V safe

Step-by-Step Assembly

Step 1: Place the Raspberry Pi Pico 2 W

Place the Raspberry Pi Pico 2 W on the breadboard so it sits across the center gap.

Keep the USB port facing outward so you can easily connect it to your computer.

Pico Placement


Step 2: Place the PIR Motion Sensor

Place the PIR motion sensor so the white dome faces the area you want to monitor.

Identify VCC, OUT, and GND before wiring.

Check the printed labels on your PIR module.

PIR Placement


Step 3: Connect PIR Power

Connect:

  • PIR VCC → 3.3V
  • PIR GND → GND

PIR Power Wiring


Step 4: Connect the PIR OUT Pin

Connect:

  • PIR OUT → GPIO 1

The output signal going into the Pico must be 3.3V safe.

PIR Signal Wiring


Wiring Check

  • Pico 2W is placed correctly across the breadboard center gap
  • PIR VCC connects to 3.3V or module-safe supply
  • PIR GND connects to GND
  • PIR OUT connects to GPIO 1
  • No loose jumper wires

Beginner Note

PIR sensors require a warm-up period after power-on. Wait a short time before testing motion detection.

Safety Note

If your PIR module outputs 5V on OUT, use a level shifter or voltage divider before connecting it to the Pico GPIO pin.


Testing Individual Components

Before running the full project, test each part separately. This makes it easier to find wiring or code problems.

PIR Sensor Test

Check that the PIR sensor detects motion before adding Wi-Fi code.

from machine import Pin
import time

pir = Pin(1, Pin.IN)

print('Wait 15 seconds for PIR warm-up')
time.sleep(15)

while True:
    print('Motion' if pir.value() else 'No motion')
    time.sleep(0.5)

Expected Test Result

The Shell should print Motion when movement is detected after the warm-up period.


Wi-Fi Connection Test

Check that the Pico connects to Wi-Fi and prints its IP address.

import network
import time

SSID = 'YOUR_WIFI_NAME'
PASSWORD = 'YOUR_WIFI_PASSWORD'

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)

for _ in range(15):
    if wlan.isconnected():
        break
    print('Connecting...')
    time.sleep(1)

print('Connected:', wlan.isconnected())

if wlan.isconnected():
    print('IP address:', wlan.ifconfig()[0])

Expected Test Result

The Shell should show Connected: True and print an IP address.


Full Project Code

import network
import socket
import time
from machine import Pin

SSID = 'YOUR_WIFI_NAME'
PASSWORD = 'YOUR_WIFI_PASSWORD'

pir = Pin(1, Pin.IN)

last_motion = 0
motion_count = 0
last_motion_time = -10000

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)

print('Connecting to Wi-Fi...')

for _ in range(15):
    if wlan.isconnected():
        break
    time.sleep(1)

if not wlan.isconnected():
    raise RuntimeError('Wi-Fi connection failed')

ip_address = wlan.ifconfig()[0]

print('Connected. Open http://{} in your browser'.format(ip_address))
print('Wait 15 seconds for PIR warm-up')

time.sleep(15)

def web_page(recent_motion, count):

    status_text = 'MOTION DETECTED!' if recent_motion else 'No Motion'
    color = '#ff5555' if recent_motion else '#44aa44'

    return """<!DOCTYPE html>
<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<meta http-equiv='refresh' content='2'>
<title>PIR Motion Alert</title>
</head>
<body style='font-family:Arial;text-align:center;padding:40px'>
<h1>PIR Motion Alert</h1>
<div style='font-size:32px;color:STATUS_COLOR'>STATUS_TEXT</div>
<p>Total detections: COUNT_TEXT</p>
<p>Page refreshes every 2 seconds</p>
</body>
</html>""".replace(
        'STATUS_TEXT', status_text
    ).replace(
        'STATUS_COLOR', color
    ).replace(
        'COUNT_TEXT', str(count)
    )

address = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

server = socket.socket()
server.bind(address)
server.listen(1)
server.settimeout(0.2)

while True:

    motion = pir.value()

    if motion == 1 and last_motion == 0:
        motion_count += 1
        last_motion_time = time.ticks_ms()
        print('Motion detected! Count:', motion_count)

    last_motion = motion

    recent_motion = (
        time.ticks_diff(
            time.ticks_ms(),
            last_motion_time
        ) < 5000
    )

    try:
        client, client_address = server.accept()
    except OSError:
        continue

    print('Client connected from', client_address)

    client.recv(1024)

    response = web_page(recent_motion, motion_count)

    client.send(
        'HTTP/1.1 200 OK\r\n'
        'Content-Type: text/html\r\n'
        'Connection: close\r\n\r\n'.encode()
    )

    client.sendall(response.encode())
    client.close()

How the Code Works

Code Section What It Does Why It Matters
PIR Input Reads the motion sensor state Provides the motion event signal
Edge Detection Counts only a new motion event when the signal changes from LOW to HIGH Prevents one long motion signal from being counted repeatedly
last_motion_time Stores when the most recent motion occurred Allows the page to show a recent alert
Web Page Response Shows current alert status and total detection count Creates a simple Wi-Fi dashboard

Expected Result

After entering your Wi-Fi details and running the code, the Shell should print an IP address.

Opening that address in a browser should show No Motion initially.

Moving in front of the PIR sensor should:

  • Increase the motion count
  • Display MOTION DETECTED!
  • Show the recent alert for a few seconds

Troubleshooting

Problem Possible Cause Solution
No motion is detected PIR still warming up or incorrect wiring Wait longer and recheck the OUT pin on GPIO 1
False triggers happen often Sensor sensitivity is too high or the area contains heat movement Reposition the PIR and reduce sensitivity
Web page never changes Motion count is not updating or browser is not refreshing Watch the Shell output and confirm the count increases