Connect Raspberry Pi Pico W with WiFi and Control LED

The following program will connect a Raspberry Pi Pico W with Wifi. Moreover, we will control the onboard LED from a browser such as Chrome/Firefox or any browser of your choice.

In the following program, you only have to change two lines.

In the “ssid” line put your WiFi name, and the password will be your WiFi password.

In this program, we are connecting our Raspberry Pi with a fixed IP address. In this case “192.168.86.99”. In this way we know for certain at which address we can access our Raspberry Pi Pico W. Otherwise the WiFi router will assign a random IP to our Pico W. Without looking into the Log, we won’t know the IP address.

However, if you want a random IP address or you don’t require a fixed IP address, you can delete the wlan.ifconfig line from the code.

It may take several seconds for the Pi Pico W to connect to WiFi.

After a successful connection, open a browser of your choice and put “192.168.86.99/on” as the address. It will turn on the onboard Pico W LED.

To turn off the LED, put 192.168.86.99/off on the browser.

Please do remember that both the Pico W and your phone or computer must be connected to the same WiFi network.

import network
from time import sleep
import machine
from machine import Pin

from microdot import Microdot

pin = Pin("LED", Pin.OUT)

ssid = 'Your WiFi Name'
password = 'Your WiFi Password'

def connect():
    #Connect to WLAN
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.ifconfig(('192.168.86.99', '255.255.255.0', '192.168.86.1', '192.168.86.1'))
    wlan.connect(ssid, password)
    while wlan.isconnected() == False:
        print('Waiting for connection...')
        sleep(1)
    print(wlan.ifconfig())

try:
    connect()
except KeyboardInterrupt:
    machine.reset()

app = Microdot()

@app.route('/on')
async def on(request):
    pin.on()
    print('Led On')

@app.route('/off')
async def off(request):
    pin.off()
    print('LED Off')


app.run(port=80)