Connect to Multiple WiFi Networks with your Raspberry Pi Pico W

Posted by Jay on May 19, 2023

Connect to Multiple WiFi Networks with your Raspberry Pi Pico W

Raspberry Pi Pico W Python CircuitPython

I've been working with the Raspberry Pi Pico W for a few weeks on various little demo projects.

One of the first things I noticed was that most of the code you find to connect the Pico to WiFi assumes that it will always be on the same network.  If you take your work home with you or just need to have your Pico W able to connect to multiple WiFi networks, this is a problem...until now!

Keep reading to see how you can preload your Raspberry Pi Pico W with as many wireless network credentials as you need to make sure it can connect wherever you are using it!

This tutorial assumes you are using CircuitPython for Raspberry Pi Pico W and the free Thonny IDE.

I'll show you 3 different methods that all work depending on your setup.

They all use the Adafruit Basic WiFi connection tutorial code as a base.

You can watch the walkthrough on YouTube  or skip below to the code:

Method 1: All in one file (simple, but less secure):

Button
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
#
# SPDX-License-Identifier: MIT

##This method loops through several SSID / Password matches in the settings.toml file

import os
import ipaddress
import wifi
import socketpool

import time

#Add your possible WiFi networks here:
wifiNetworks = {
   'Network1' : '123456789',
   'Network2' : '123456789'
}

print()
print("Attempting to connect to WiFi...")
print()

wifiConnect = False #flag to see if we are already connected

for ssid, password in wifiNetworks.items():
    ##Try next SSID
    if not wifiConnect:
        print("Trying to connect to: " + ssid)
        time.sleep(.1)
        try:
            wifi.radio.connect(ssid,password)
            print("Success! Connected to WiFi network: " + ssid)
            wifiConnect = True #Mark flag so we can stop trying to connect
            pool = socketpool.SocketPool(wifi.radio)
            #  prints MAC address to REPL
            print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])
            #  prints IP address to REPL
            print("My IP address is", wifi.radio.ipv4_address)
        except:
            print("Failed to connect to: " + ssid)

#Pause if still not connected:
if not wifiConnect:
    print("=============================================")
    print("Failed to connect to all known WiFi networks!")
    print("=============================================")
    time.sleep(60)

 

Method 2: Separate credentials file:

Step 1: Create a file named secret.py and place your wifi network info in it:

Button
wifiNetworks = {
   'Network1' : '123456789',
   'Network2' : '123456789'
}

Step 2: import the secret file into your main python file:

Button
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
#
# SPDX-License-Identifier: MIT

##This method loops through several SSID / Password matches in the secret.py file

import os
import ipaddress
import wifi
import socketpool

import time, secret

print()
print("Attempting to connect to WiFi...")
print()

wifiConnect = False #flag to see if we are already connected

for ssid, password in secret.wifiNetworks.items():
    ##Try next SSID
    if not wifiConnect:
        print("Trying to connect to: " + ssid)
        time.sleep(.1)
        try:
            wifi.radio.connect(ssid,password)
            print("Success! Connected to WiFi network: " + ssid)
            wifiConnect = True #Mark flag so we can stop trying to connect
            pool = socketpool.SocketPool(wifi.radio)
            #  prints MAC address to REPL
            print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])
            #  prints IP address to REPL
            print("My IP address is", wifi.radio.ipv4_address)
        except:
            print("Failed to connect to: " + ssid)

#Pause if still not connected:
if not wifiConnect:
    print("=============================================")
    print("Failed to connect to all known WiFi networks!")
    print("=============================================")
    time.sleep(60)


Method 3: Using a settings.toml file to hold wifi information:

settings.toml file:

**Note that you'll need to change the variable number based on how many network pairs you are supplying**

Button
CIRCUITPY_NETWORK_COUNT = 2

CIRCUITPY_WIFI_SSID1 = "Network_One"
CIRCUITPY_WIFI_PASSWORD1 = "password1"

CIRCUITPY_WIFI_SSID2 = "Network_Two"
CIRCUITPY_WIFI_PASSWORD2 = "password2"

code.py file contents:

Button
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
#
# SPDX-License-Identifier: MIT

##This method loops through several SSID / Password matches in the settings.toml file

import os
import ipaddress
import wifi
import socketpool

import time

print()
print("Attempting to connect to WiFi...")
print()

wifiConnect = False #flag to see if we are already connected

networkPool = os.getenv('CIRCUITPY_NETWORK_COUNT')

for networkNum in range(1, int(networkPool) + 1):        
    ##Try next SSID
    if not wifiConnect:
        try:
            thisSID = "CIRCUITPY_WIFI_SSID" + str(networkNum)
            thisKey = "CIRCUITPY_WIFI_PASSWORD" + str(networkNum)
            wifi.radio.connect(os.getenv(thisSID), os.getenv(thisKey))
            print("Success! Connected to WiFi network: " + os.getenv(thisSID))
            wifiConnect = True #Mark flag so we can stop trying to connect
            pool = socketpool.SocketPool(wifi.radio)
            #  prints MAC address to REPL
            print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])
            #  prints IP address to REPL
            print("My IP address is", wifi.radio.ipv4_address)
        except:
            print("Failed to connect to Wifi network: " + os.getenv(thisSID))

#Pause if still not connected:
if not wifiConnect:
    print("=============================================")
    print("Failed to connect to all known WiFi networks!")
    print("=============================================")
    time.sleep(60)





Other Info:

Here are some other things to know about...