Skip to content

Wi-Fi Button Press Logger

Project 44 • Beginner

Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython


Property Value
Manual Section Beginner Projects
Project Level Beginner
Board Raspberry Pi Pico 2 W
Programming Language MicroPython
Version 1.0
Date May 2026
Prepared for STEMAIDE Africa

Overview

Build a button logger that shows recent button presses on a web page.

This project demonstrates edge detection, event history, and simple time tracking since boot.

The final result should show the last 10 button press times on a local web page.

!!! note "Project Story" Beginner Extension Project: This project is more advanced than the earlier beginner projects. Complete the basic projects first before attempting this one.

Required Components

Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
Push button
Push button
Breadboard
Breadboard
Jumper wires
Jumper wires

Circuit Connections

Component Pin Connects To Pico GPIO / Physical Pin Number Notes
Button leg 1 GPIO 15 GPIO 15 / physical pin 20 Use internal pull-up in code
Button opposite leg GND Physical pin 38 —

Step-by-Step Assembly

Step 1: Place the Raspberry Pi Pico 2W

Place the Raspberry Pi Pico 2W 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.

circuit_2

Step 2: Place the Push Button

  • Place the push button across the breadboard center gap.
  • This keeps the two sides of the button on separate breadboard rows.
  • No external pull-up resistor is needed because the code uses the Pico internal pull-up.

circuit_3

Step 3: Connect the Button Signal Leg

  • Connect one button leg to GPIO 15.
  • Connect the opposite button leg to GND.

circuit_4


Wiring Check

Pico 2W is placed correctly across the breadboard center gap
Push button sits across the breadboard center gap
Button signal leg connects to GPIO 15
Button opposite leg connects to GND
No loose jumper wires

!!! note "Beginner Note" If button counts jump by more than one, the switch may be bouncing. The code can use a short delay to make readings steadier.


Testing Individual Components

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

Button Test

Check that the button reads correctly before adding Wi-Fi and logging code.

from machine import Pin
import time

button = Pin(15, Pin.IN, Pin.PULL_UP)

while True:
    print('Pressed' if button.value() == 0 else 'Released')
    time.sleep(0.2)

Expected test result: The Shell should change between Released and Pressed.

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

Upload and run this code after the individual tests work correctly.

import network
import socket
import time
from machine import Pin

SSID = 'YOUR_WIFI_NAME'
PASSWORD = 'YOUR_WIFI_PASSWORD'

button = Pin(15, Pin.IN, Pin.PULL_UP)
presses = []
MAX_PRESSES = 10
last_button_state = 1
start_ms = time.ticks_ms()

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))


def elapsed_timestamp():
    total_seconds = time.ticks_diff(time.ticks_ms(), start_ms) // 1000
    minutes = total_seconds // 60
    seconds = total_seconds % 60
    return '{:02d}:{:02d} since boot'.format(minutes, seconds)


def web_page(log_entries):
    rows = ''
    for index, text in enumerate(reversed(log_entries), 1):
        rows += '<tr><td>{}</td><td>{}</td></tr>'.format(index, text)

    if not rows:
        rows = "<tr><td colspan='2'>No button presses recorded yet</td></tr>"

    return '''<!DOCTYPE html>
<html>
<head>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <meta http-equiv='refresh' content='2'>
    <title>Wi-Fi Button Logger</title>
</head>
<body style='font-family:Arial;text-align:center;padding:30px'>
    <h1>Wi-Fi Button Logger</h1>
    <p>Press the physical button to create a log entry.</p>
    <table border='1' cellpadding='8' cellspacing='0' style='margin:0 auto'>
        <tr><th>#</th><th>Time</th></tr>
        LOG_ROWS
    </table>
    <p>Showing the last MAX_TEXT entries</p>
    <a href='/clear'><button style='margin-top:20px;padding:10px 20px'>Clear Log</button></a>
</body>
</html>'''.replace('LOG_ROWS', rows).replace('MAX_TEXT', str(MAX_PRESSES))


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:
    current_state = button.value()

    if current_state == 0 and last_button_state == 1:
        stamp = elapsed_timestamp()
        presses.append(stamp)

        if len(presses) > MAX_PRESSES:
            presses.pop(0)

        print('Button pressed at', stamp)
        time.sleep(0.15)

    last_button_state = current_state

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

    print('Client connected from', client_address)
    request = client.recv(1024).decode()

    if 'GET /clear' in request:
        presses = []
        print('Log cleared')

    response = web_page(presses)
    client.send('HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n'.encode())
    client.sendall(response.encode())
    client.close()

How the Code Works

Code Section What It Does Why It Matters
Pin.PULL_UP Keeps the button input high when the button is not pressed No external pull-up resistor is needed
Edge detection Logs only when the button changes from released to pressed This prevents many log entries from one long press
elapsed_timestamp() Creates a simple time label since the Pico started This avoids pretending the Pico knows real clock time when no RTC is set
presses list Stores only the most recent log entries The web page stays easy to read

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 a log table. Pressing the physical button should add a new entry to the table.


Troubleshooting

Problem Possible Cause Solution
No log entries appear Button wiring is wrong or page is not refreshing Check GPIO 15, GND, and the auto-refresh behavior
Many entries appear from one press Button bounce is causing extra edges Keep the short debounce delay and press more slowly while testing
Timestamps look strange They are relative to boot, not real clock time This is expected unless you add a real-time clock or NTP sync later