Raspberry Pi Pico W: Getting Started with Wi-Fi (MicroPython)

The Raspberry Pi Pico W comes with the Infineon CYW43439 chip that contains a 2.4 GHz radio providing 802.11n Wi-Fi. This tutorial is an introduction to Wi-Fi on the Raspberry Pi Pico W using MicroPython. We’ll cover setting the Pico as a Wi-Fi station and as an Access Point (AP), scanning for nearby Wi-Fi networks, connecting your Pico to your local network, and getting information about its IP address.

Raspberry Pi Pico W Getting Started with Wi-Fi MicroPython

New to the Raspberry Pi Pico? Get started here: Get started with the Raspberry Pi Pico here.

Table of Contents:

Prerequisites – MicroPython Firmware

To follow this tutorial you need MicroPython firmware installed in your Raspberry Pi Pico board. You also need an IDE to write and upload the code to your board.

The recommended MicroPython IDE for the Raspberry Pi Pico is Thonny IDE. Follow the next tutorial to learn how to install Thonny IDE, flash MicroPython firmware, and upload code to the board.

Wi-Fi Station and Wi-Fi Access Point

The Raspberry Pi Pico can act as a Wi-Fi station, or as a Wi-Fi access point.

Wi-Fi Station

When the Pico is set as a Wi-Fi station, it can connect to other networks (like your router—local network). In this scenario, the router assigns a unique IP address to your board. You can communicate with the Raspberry Pi Pico using other devices (stations) that are also connected to the same network by referring to the Raspberry Pi Pico’s local IP address.

Raspberry Pi Pico Wi-Fi Station

Since the router is also connected to the internet, we can request information from the internet using our board, like data from APIs (weather data, for example), publish data to online platforms, use icons and images from the internet in our web server pages or include JavaScript libraries.

However, in some cases, we may not have a router nearby to connect the Raspberry Pi Pico. In this scenario, you can set your board as an access point.

Access Point (AP)

When your Pico is set up as an Access Point (AP), other devices (such as your smartphone, tablet, or computer) can connect to it without the need for a router; the Pico creates its own Wi-Fi network. Unlike a router, an Access Point doesn’t connect further to a wired network or the Internet, so you can’t access external libraries, publish sensor readings to the cloud, or use services like mail.

Raspberry Pi Pico as an access point

Station and Access Point Interfaces

There is a MicroPython module called network that is used to configure and handle everything Wi-Fi-related. There are two Wi-Fi interfaces, one for the station and another for the access point. The following example creates a station interface and an access point interface and checks if they are active.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-w-wi-fi-micropython/

import network

sta_if = network.WLAN(network.STA_IF)
print(sta_if.active())

ap_if = network.WLAN(network.AP_IF)
print(ap_if.active())

View raw code

After running this example, you should get something as follows.

Rpi Pico Checking Wi-Fi Station and access point interfaces

At the moment, you don’t have any active interface.


Scanning Nearby Wi-Fi Networks

To scan for nearby Wi-Fi networks, we must start a Wi-Fi interface station network first. For example:

# Init Wi-Fi interface
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

Then we can use wlan.scan() to scan for nearby networks. This command returns a list of named tuples that include SSDI, BSSID, RSSI, Wi-Fi channel, and other details.

# Scan for available Wi-Fi networks
networks = wlan.scan()

Then, we can go through all the returned networks and print their info. The complete code can be found below.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-w-wi-fi-micropython/

import network

# Init Wi-Fi interface
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

# Scan for Wi-Fi networks
networks = wlan.scan()

# Print Wi-Fi networks
print("Available WiFi Networks:")
for network_info in networks:
    print(network_info)

View raw code

Run the previous code on your Raspberry Pi Pico. It should return a list of nearby Wi‑Fi networks and corresponding info. The network information is separated by commas and is in the following order: SSDI, BSSID, RSSI, channel.

RPi Pico Scanning Wi-Fi Networks

The RSSI is the received signal strength indicator and it shows how strong is the Wi‑Fi signal. The lower the value, the worse the signal.

As for the last two numbers, at the moment, the documentation is not clear what those numbers exactly mean. Supposedly they represent the auth mode and if the network is hidden or not. Unfortunately, the values we get don’t match the range in the documentation. So, they either represent something different, or there is some sort of bug.


Connecting the Raspberry Pi Pico to a Wi-Fi Network

Connecting your Pico board to your Wi-Fi network is very straightforward thanks to the network MicroPython module. To connect to your network, you need to know the SSID (the name of your Wi-Fi network) and password.

When a device connects to a network, the router assigns an IP address to that device. All devices connected to a network, have a unique IP address. So, when you connect the Raspberry Pi Pico to your router, it will assign it a unique IP address on your network.

The following example connects the Raspberry Pi Pico to your network and prints the IP address assigned to the Pico on your network.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-w-wi-fi-micropython/

import network
from time import sleep
# Wi-Fi credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

# Init Wi-Fi Interface
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

# Connect to your network
wlan.connect(ssid, password)

# Wait for Wi-Fi connection
connection_timeout = 10
while connection_timeout > 0:
    if wlan.status() >= 3:
        break
    connection_timeout -= 1
    print('Waiting for Wi-Fi connection...')
    sleep(1)

# Check if connection is successful
if wlan.status() != 3:
    raise RuntimeError('Failed to establish a network connection')
else:
    print('Connection successful!')
    network_info = wlan.ifconfig()
    print('IP address:', network_info[0])

View raw code

How the Code Works

Let’s take a quick look at how this previous code works.

Importing the network module

First, you need to import the network module.

import network

The network module provides several methods to create and handle the Wi-Fi interfaces and connections.

Inserting your Wi-Fi Credentials

In the following two variables, you must insert your network SSID and password.

# Wi-Fi credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

Connecting to the Internet

Create a station network interface and then activate it.

# Init Wi-Fi Interface
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

Then, use that interface to connect to your home network using the SSID and password you defined earlier.

# Connect to your network
wlan.connect(ssid, password)

Checking the Connection Status and Printing the IP Address

Then, we’ll check the connection status and print the IP address when we successfully connect.

# Wait for Wi-Fi connection
connection_timeout = 10
while connection_timeout > 0:
    if wlan.status() >= 3:
        break
    connection_timeout -= 1
    print('Waiting for Wi-Fi connection...')
    sleep(1)

# Check if connection is successful
if wlan.status() != 3:
    raise RuntimeError('Failed to establish a network connection')
else:
    print('Connection successful!')
    network_info = wlan.ifconfig()
    print('IP address:', network_info[0])

The code first checks the connection status, and if it’s wlan.status() >= 3 (this means it has even connected to the network or failed to connect), the loop exits. It waits for a maximum of 10 seconds (10 attempts defined in the connection_timeout variable).

The method wlan.status(), as the name suggests, checks the status of the Wi-Fi connection of the Raspberry Pi. This method returns an integer with the following meaning:

  • 0: WLAN is not enabled
  • 1: WLAN is currently scanning for networks
  • 2: WLAN is connecting to a network
  • 3: WLAN is connected to a network
  • 4: WLAN failed to connect to a network

Then, we check if it’s connected or not (we know that status = 3 means it’s connected). If wlan.status() is different than 3, we know it failed to establish a connection.

if wlan.status() != 3:
    raise RuntimeError('Failed to establish a network connection')

Otherwise, it means we succeed. In case we succeed, we can get the network information using the ifconfig() method. This method returns a tuple with the following information:

  • network_info[0]: The IP address assigned to the Pico on the network.
  • network_info[1]: The subnet mask.
  • network_info[2]: The gateway IP address.
  • network_info[3]: The DNS (Domain Name System) server IP address.

We just need the IP address, so we just get the first element of the array (network_info[0]).

else:
    print('Connection successful!')
    network_info = wlan.ifconfig()
    print('IP address:', network_info[0])

The isconnected() method

Instead of checking the connection status, the wlan object supports a method called isconnected() that returns True if the board is connected to the network or False otherwise.You can use that approach instead of checking wlan.status().

Testing the Code

Run the previous code. Don’t forget to replace the ssid and password variables with your network details.

# Wi-Fi credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

After a few attempts, it should connect to your network and display the IP address.

Raspberry Pi Pico: connect to network and get ip address

Troubleshooting

If you’re Raspberry Pi Pico is not connecting to your network:

  • check that you’re inserting the right SSID and password; spaces and uppercase/lowercase matter;
  • check that your network is showing up when we scanned for Wi-Fi networks previously;
  • make sure the Raspberry Pi Pico is relatively close to your router so that it can catch the Wi-Fi signal.

Setting a Static IP Address to the Raspberry Pi Pico

In the case of my network, even if I restart the Raspberry Pi Pico several times, my router will always assign it the same IP address. However, that’s not the case for some other networks. In that scenario, it’s nice to have a way to set a static IP address to your board, so that it doesn’t change every time it resets. Additionally, it might also be useful for projects that are not connected to your computer or don’t have a way to display the IP address.

You can use the ifconfig method of the network.WLAN object to set a static IP address.

We can easily modify the previous example with just a few lines to set a static IP address.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-w-wi-fi-micropython/

import network
import time

# Wi-Fi credentials
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'

# Static IP configuration
static_ip = '192.168.1.100'  # Replace with your desired static IP
subnet_mask = '255.255.255.0'
gateway_ip = '192.168.1.254'
dns_server = '8.8.8.8'

# Init Wi-Fi Interface
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

# Connect to your network
wlan.connect(ssid, password)

# Wait for Wi-Fi connection
connection_timeout = 10
while connection_timeout > 0:
    if wlan.status() >= 3:
        break
    connection_timeout -= 1
    print('Waiting for Wi-Fi connection...')
    time.sleep(1)

# Set static IP address
wlan.ifconfig((static_ip, subnet_mask, gateway_ip, dns_server))

# Check if connection is successful
if wlan.status() != 3:
    raise RuntimeError('Failed to establish a network connection')
else:
    print('Connection successful!')
    network_info = wlan.ifconfig()
    print('IP address:', network_info[0])

View raw code

Static IP Configuration

Replace the values in the static_ip, subnet_mask, gateway_ip, and dns_server variables with the appropriate values for your network.

# Static IP configuration
static_ip = '192.168.1.100'  # Replace with your desired static IP
subnet_mask = '255.255.255.0'
gateway_ip = '192.168.1.254'
dns_server = '8.8.8.8'

How to find those values?

There are different ways to get information about the subnet mask and the gateway IP. The easiest way is to open a Terminal window on your computer and run the following command:

On Windows:

ipconfig

On MacOS or Linux:

ifconfig
ipconfig commang

It will return the information you’re looking for: the gateway IP (the IP address of your router) and the subnet mask.

ipconfig wlan details

In my case, the subnet mask is 255.255.255.0 and the gateway IP address is 192.168.1.254.

For the DNS server, you can always use 8.8.8.8, which is Google’s public DNS server.

When choosing the static IP address for your Raspberry Pi Pico, make sure that the address is not already being used by another device. To do that, you can use a software like Angry IP Scanner (compatible with Windows and Mac OS). Or you can login into your router dashboard and check which IP addresses are already assigned.

Setting a Static IP Address

After assigning the proper values for the configuration variables, we can simply use the ifconfig() method and pass as arguments the static IP, the subnet mask, the gateway IP, and the DNS server, in this order.

wlan.ifconfig((static_ip, subnet_mask, gateway_ip, dns_server))

Testing the Code

After inserting your network credentials and desired IP address settings, you can run the code on your Raspberry Pi Pico.

Notice that it will have the IP address you defined on the code assigned to it. In our case, 192.168.1.100.

Raspberry Pi Pico Set Static IP address

Wrapping Up

This tutorial was a quick getting started guide for Wi-Fi on the Raspberry Pi Pico programmed with MicroPython. We hope you find it useful.

You may also like other Wi-Fi-related tutorials with the Raspberry Pi Pico:

Learn more about the Raspberry Pi Pico with our resources:

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

1 thought on “Raspberry Pi Pico W: Getting Started with Wi-Fi (MicroPython)”

  1. As always, thanks for sharing!!

    I’d add the following lines to make the WiFi connection even more stable for a Pico W board:

    import rp2
    import time

    Init Wi-Fi Interface

    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    time.sleep_ms(500)
    rp2.country(‘ES’) # ES for Spain
    wlan.config(pm = 0xa11140) # turn off power savings
    wlan.connect(ssid, password)

    time.sleep(3)

    Best regards.

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.