Skip to content

Wi-Fi Relay Scheduler

Project 51 • 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 relay scheduler that uses Wi-Fi time sync, local buttons, an OLED display, and a browser page.

This project demonstrates using internet time to trigger relay actions at chosen times of day.

The final result should show the current time on the OLED, allow manual control from buttons or browser, and switch the relay automatically when a scheduled time is reached.

!!! 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
1-channel relay module
1-channel relay module
SH1106 OLED display
SH1106 OLED display
Push buttons
Push buttons
Breadboard
Breadboard
Jumper wires
Jumper wires

Circuit Connections

Component Pin Connects To Pico GPIO / Physical Pin Number Notes
Relay VCC 5V / VSYS Physical pin 40 Module power
Relay GND GND Physical pin 38 —
Relay IN GPIO 0 GPIO 0 / physical pin 1 Usually active-low
OLED VCC 3.3V Physical pin 36 —
OLED GND GND Physical pin 38 —
OLED SDA GPIO 8 GPIO 8 / physical pin 11 I2C0 SDA
OLED SCL GPIO 9 GPIO 9 / physical pin 12 I2C0 SCL
Manual ON button leg 1 GPIO 15 GPIO 15 / physical pin 20 Use internal pull-up
Manual ON 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 Relay Module, OLED, and Buttons

  • Place the 1-channel relay module on the breadboard or beside it where the pins are easy to reach.
  • Place the SH1106 OLED display module on the breadboard.
  • Place the two push buttons across the breadboard center gap.
  • Identify relay VCC, GND, IN, COM, NO, and NC before wiring any load side connections.

circuit_3

Step 3: Connect Relay Power

  • Connect relay VCC to 5V / VSYS.
  • Connect relay GND to GND.

circuit_4

Step 4: Connect the Relay IN Pin

  • Connect relay IN to GPIO 0.

Step 5: Connect OLED Power

  • Connect OLED VCC to 3.3V.
  • Connect OLED GND to GND.

Step 6: Connect OLED I2C Pins

  • Connect OLED SDA to GPIO 8.
  • Connect OLED SCL to GPIO 9.

Step 7: Connect the Manual ON Button

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

circuit_5

Step 8: Optional


Wiring Check

Pico 2W is placed correctly across the breadboard center gap
Relay VCC connects to 5V / VSYS
Relay GND connects to GND
Relay IN connects to GPIO 0
OLED VCC connects to 3.3V
OLED GND connects to GND
OLED SDA connects to GPIO 8
OLED SCL connects to GPIO 9
Manual button connects to GPIO 15 and GND
No loose jumper wires

!!! warning "Safety Note" Use only low-voltage loads in this beginner relay project. Do not connect mains AC power to the relay.


Testing Individual Components

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

Relay Click Test

Check that the relay changes state before using schedule code.

from machine import Pin
import time

relay = Pin(0, Pin.OUT)
relay.value(1)
time.sleep(1)
relay.value(0)
time.sleep(1)
relay.value(1)

Expected test result: You should hear the relay click on and off.

Button Test

Check that the ON and OFF buttons read correctly.

from machine import Pin
import time

btn_on = Pin(15, Pin.IN, Pin.PULL_UP)
btn_off = Pin(16, Pin.IN, Pin.PULL_UP)

while True:
    print('ON button:', btn_on.value(), 'OFF button:', btn_off.value())
    time.sleep(0.2)

Expected test result: The printed values should change from 1 to 0 when each button is pressed.

OLED I2C Scanner Test

Check that the OLED appears on the I2C bus.

from machine import I2C, Pin

i2c = I2C(0, sda=Pin(8), scl=Pin(9), freq=400000)
print([hex(addr) for addr in i2c.scan()])

Expected test result: You should usually see the OLED address such as 0x3c.

OLED Text Test

Check that the OLED driver works.

from machine import I2C, Pin
import sh1106

i2c = I2C(0, sda=Pin(8), scl=Pin(9), freq=400000)
oled = sh1106.SH1106_I2C(128, 64, i2c)
oled.fill(0)
oled.text('Scheduler OK', 12, 28, 1)
oled.show()

Expected test result: The OLED should show Scheduler OK.

Wi-Fi and NTP Test

Check that the Pico connects to Wi-Fi and can try time sync.

import network
import ntptime
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
    time.sleep(1)

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

if wlan.isconnected():
    try:
        ntptime.settime()
        print('NTP sync OK')
        print(time.localtime())
    except Exception as error:
        print('NTP sync failed:', error)

Expected test result: The Shell should show Connected: True and either sync time successfully or print an NTP error message.


Full Project Code

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

import network
import ntptime
import socket
import time
from machine import I2C, Pin
import sh1106

# =========================

# Wi-Fi Credentials

# =========================
SSID = 'YOUR_WIFI_NAME'
PASSWORD = 'YOUR_WIFI_PASSWORD'

# =========================

# Relay Setup

# Active LOW relay:

# 0 = ON

# 1 = OFF

# =========================
relay = Pin(0, Pin.OUT)
relay.value(1)

# =========================

# Single Toggle Button

# =========================
btn_toggle = Pin(15, Pin.IN, Pin.PULL_UP)

# =========================

# OLED Setup

# =========================
i2c = I2C(0, sda=Pin(8), scl=Pin(9), freq=400000)
oled = sh1106.SH1106_I2C(128, 64, i2c)

# =========================

# Timezone Offset

# Ghana = 0

# Example:

# Nigeria = 1

# India = 5

# =========================
TIMEZONE_OFFSET = 0

# =========================

# Relay Schedule

# Format:

# (hour, minute, action)

# action:

# 1 = ON

# 0 = OFF

# =========================
schedule = [
    (7, 0, 1),
    (8, 30, 0),
    (18, 0, 1),
    (22, 0, 0),
]

# =========================

# Time Functions

# =========================
def local_hour_minute():
    now = time.localtime()
    hour = (now[3] + TIMEZONE_OFFSET) % 24
    minute = now[4]
    return hour, minute

# =========================

# Relay Control

# =========================
def relay_on():
    relay.value(0)

def relay_off():
    relay.value(1)

def relay_toggle():
    if relay.value() == 1:
        relay_on()
    else:
        relay_off()

def relay_status_text():
    return 'ON' if relay.value() == 0 else 'OFF'

# =========================

# OLED Display

# =========================
def update_oled():
    hour, minute = local_hour_minute()

    oled.fill(0)

    oled.text('Relay Scheduler', 0, 0, 1)
    oled.text('{:02d}:{:02d}'.format(hour, minute), 32, 18, 1)
    oled.text('Relay: ' + relay_status_text(), 10, 42, 1)

    oled.show()

# =========================

# Web Page

# =========================
def web_page():
    hour, minute = local_hour_minute()

    return '''<!DOCTYPE html>
<html>
<head>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <meta http-equiv='refresh' content='5'>
    <title>Relay Scheduler</title>
</head>

<body style='font-family:Arial;text-align:center;padding:30px;background:#f2f2f2;'>

    <h1>Wi-Fi Relay Scheduler</h1>

    <h2>{:02d}:{:02d}</h2>

    <p><b>Relay State:</b> {}</p>

    <p>
        <a href='/on'>
            <button style='padding:15px 30px;font-size:18px;'>ON</button>
        </a>

        <a href='/off'>
            <button style='padding:15px 30px;font-size:18px;'>OFF</button>
        </a>
    </p>

    <h3>Schedule</h3>

    <p>07:00 ON</p>
    <p>08:30 OFF</p>
    <p>18:00 ON</p>
    <p>22:00 OFF</p>

</body>
</html>
'''.format(hour, minute, relay_status_text())

# =========================

# Connect to Wi-Fi

# =========================
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')

print('Wi-Fi Connected')

# =========================

# Sync Time from Internet

# =========================
try:
    ntptime.settime()
    print('Time synced with NTP')

except Exception as error:
    print('NTP sync failed:', error)

# =========================

# Show IP Address

# =========================
ip_address = wlan.ifconfig()[0]

print('Open this in browser:')
print('http://{}'.format(ip_address))

# =========================

# Start Web Server

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

server = socket.socket()

server.bind(address)
server.listen(1)

server.settimeout(0.2)

print('Web server started')

# =========================

# Schedule Tracking

# =========================
last_checked_minute = None

# =========================

# Main Loop

# =========================
while True:

    # =====================
    # Single Button Toggle
    # =====================
    if btn_toggle.value() == 0:

        time.sleep_ms(50)

        if btn_toggle.value() == 0:

            relay_toggle()

            print('Button Toggle:', relay_status_text())

            # Wait until released
            while btn_toggle.value() == 0:
                pass

            time.sleep_ms(50)

    # =====================
    # Schedule Control
    # =====================
    current_hour, current_minute = local_hour_minute()

    minute_signature = (current_hour, current_minute)

    if minute_signature != last_checked_minute:

        for schedule_hour, schedule_minute, action in schedule:

            if (current_hour == schedule_hour and
                    current_minute == schedule_minute):

                if action == 1:
                    relay_on()
                else:
                    relay_off()

                print('Schedule Action:',
                      'ON' if action == 1 else 'OFF')

        last_checked_minute = minute_signature

    # =====================
    # Update OLED
    # =====================
    update_oled()

    # =====================
    # Handle Web Requests
    # =====================
    try:
        client, client_address = server.accept()

    except OSError:
        continue

    request = client.recv(1024).decode()

    if 'GET /on' in request:
        relay_on()

    elif 'GET /off' in request:
        relay_off()

    response = web_page()

    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
Schedule list Stores times and relay actions This is the core of the scheduler project
NTP sync Tries to get the current time from the internet The schedule needs a real time reference
Manual controls Allow the relay to be switched by buttons or browser This gives the user control outside the schedule
OLED update Shows the current time and relay state The scheduler becomes easier to observe locally

Expected Result

After entering your Wi-Fi details and running the code, the Shell should print an IP address and try time sync. The OLED should show the current time and relay state. The browser and physical buttons should control the relay, and the relay should also change automatically when a scheduled time is reached.


Troubleshooting

Problem Possible Cause Solution
Time is wrong Timezone offset is not set for your location Adjust TIMEZONE_OFFSET in the code
NTP sync fails The board has Wi-Fi but cannot reach the time server Check internet access on the network and try again
OLED is blank Wrong I2C pins or missing sh1106.py Use GPIO 8/9 and confirm sh1106.py is on the Pico
Schedule does not trigger Current time or schedule list does not match Print the current hour and minute and compare them with the schedule entries