Raspberry Pi Pico W
Connecting To The Internet

Once you have the MicroPython firmware installed, you will want to test out connecting to a wireless network. To help with sharing your projects, it makes sense to make a separate file with the information that you don't want to share. I save this file to my lib folder and call it secrets.py. This file consists of a single dictionary object in which you define the values you need for your connection. In later projects, I will put in API tokens and other things that are specific to my online accounts. Clearly, you need to add your own details here. This could be for your home WiFi network or you could put in the details for a personal hotspot that you create on your mobile phone, which will also work.

secrets = {
    'ssid' : 'YOUR SSID',
    'password' : 'YOUR PASSWORD'
    }

This is a basic script for connecting in your main.py. It is based on what you find in the documentation that is produced by the Raspberry Pi team. It makes 10 attempts at connecting and raises an error if it can't connect in that time.

# basic connection script
from time import sleep
from network import WLAN, STA_IF
from secrets import secrets

wlan = WLAN(STA_IF)
wlan.active(True)
wlan.connect(secrets["ssid"], secrets["password"])

# try to connect or fail
max_wait = 10
while max_wait >0:
    if wlan.status() <0 or wlan.status()>=3:
        break
    max_wait -= 1
    print("Waiting for connection...")
    sleep(1)

# connection error
if wlan.status() != 3:
    raise RuntimeError("Network connection failed.")
else:
    status = wlan.ifconfig()
    print("Connected to", secrets["ssid"], "on", status[0])

I prefer to use a function and, rather than generate the error, give myself a simple way to determine in the program if I have managed to get a network connection.

from time import sleep
from network import WLAN, STA_IF
from secrets import secrets


wlan = WLAN(STA_IF)

def connect():
    wlan.active(True)
    wlan.config(pm = 0xa11140)
    wlan.connect(secrets["ssid"], secrets["password"])

    # try to connect or fail
    max_wait = 10
    while max_wait >0:
        if wlan.status() <0 or wlan.status()>=3:
            break
        max_wait -= 1
        print("Waiting for connection...")
        sleep(1)

    # connection error
    if wlan.status() != 3:
        return False
    else:
        status = wlan.ifconfig()
        print("Connected to", secrets["ssid"], "on", status[0])
        print()
        return True

if not connect():
    print("Couldn't connect to WiFi.")
else:
    print("Success.")
    wlan.disconnect()
    print("Disconnected.")

This last program will make the connection, show you the IP address that has been allocated to the Pico W and then disconnect from the network.