Raspberry Pi Pico W: Save Network Credentials on a Separate File (MicroPython)

In this quick guide for the Raspberry Pi Pico W, you’ll learn how to save your network credentials in a separate file saved on the Pico’s filesystem (in addition to your main.py script).

When creating networking projects, it might be useful to save configuration settings, such as the SSID and password, in a separate file stored on the Pico’s filesystem. Then, you can easily reference that file in your main code to use those credentials. This is not only practical but also prevents you from accidentally sharing your network credentials or sensitive information when sharing your code with a friend or online.

Raspberry Pi Pico W Save Network Credentials on a Separate File MicroPython

New to the Raspberry Pi Pico? Start here: Getting Started with Raspberry Pi Pico 2 and Pico 2 W

Prerequisites

To follow this tutorial, you need:

1) A Raspberry Pi Pico W or Raspberry Pi Pico 2W board (these models support Wi-Fi).

2) MicroPython firmware installed on your Raspberry Pi Pico board, and an IDE to write and upload code. Follow this tutorial: Programming Raspberry Pi Pico using MicroPython.

Creating a Configuration File

1. Open Thonny IDE and establish a connection with your Raspberry Pi Pico W.

2. Create a new file.

3. Write the following inside that file, but replace it with your network credentials:

wifi_ssid = 'REPLACE_WITH_YOUR_SSID'
wifi_password = 'REPLACE_WITH_YOUR_PASSWORD'

4. Save the file on the Raspberry Pi Pico filesystem. In Thonny IDE, go to File > Save as... > Raspberry Pi Pico and save the file with the name config.py.

Save File to Raspberry Pi Pico - Thonny IDE
Save config.py file to Pico's filesystem on Thonny IDE

Importing the Network Credentials

After creating the file with your network credentials, you can easily import them to your main code as follows:

from config import wifi_ssid, wifi_password

Then, you can use the wifi_ssid, and wifi_password variables to initialize Wi-Fi, when calling the wlan.connect() function.

wlan.connect(wifi_ssid, wifi_password)

Web Server with config.py File

To show you how to apply this in a practical example, here’s a simple “Hello, World” web server script that uses the SSID and password credentials from the external file to connect to the internet.

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details: https://RandomNerdTutorials.com/raspberry-pi-pico-w-save-network-credentials/

import network
import socket
import time
import random

# Import SSID and password from the config.py file
from config import wifi_ssid, wifi_password

# HTML template for the webpage
webpage = """
        <!DOCTYPE html>
        <html>
        <head>
            <title>Pico Web Server</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
        </head>
        <body>
            <h1>Raspberry Pi Pico Web Server</h1>
            <p>Hello, World!</p>
        </body>
        </html>
        """

# Init Wi-Fi Interface
def init_wifi(ssid, password):
    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)
    # Check if connection is successful
    if wlan.status() != 3:
        return False
    else:
        print('Connection successful!')
        network_info = wlan.ifconfig()
        print('IP address:', network_info[0])
        return True

if init_wifi(wifi_ssid, wifi_password):
    # Set up socket and start listening
    addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen()
    print('Listening on', addr)

# Main loop to listen for connections
while True:
    try:
        conn, addr = s.accept()
        print('Got a connection from', addr)

        # Receive and parse the request
        request = conn.recv(1024)
        request_str = request.decode('utf-8')
        print('Request content:')
        
        # Split headers and body
        headers, body = request_str.split('\r\n\r\n', 1)
        print('Headers:\n', headers)
        print('Body:\n', body)

        # Generate HTML response
        response = webpage

        # Send the HTTP response and close the connection
        conn.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
        conn.send(response)
        conn.close()

    except OSError as e:
        conn.close()
        print('Connection closed')

View raw code

Run this previous code on your Raspberry Pi Pico.

Thonny IDE Green Run Button

After a while, it will connect to your network and display its IP address.

RPi Pico Connecting Successfully to Wi-Fi Network and printing its IP address

You can access the web server on your web browser by typing the IP address.

Raspberry Pi Pico Hello World Web Server

As you can see, there’s no need to insert the credentials in your main code if you have stored them in an external file that is saved on the Pico filesystem and referenced in the main code.


Saving Multiple Network Credentials

Instead of saving a single SSID and password combination, it might be beneficial to use multiple combinations. To do that, you can create a JSON file with multiple SSID and password combinations.

Creating a JSON File

Create a new file on Thonny IDE with the following content.

[
    {"ssid": "your_ssid_1", "password": "your_password_1"},
    {"ssid": "your_ssid_2", "password": "your_password_2"},
    {"ssid": "your_ssid_3", "password": "your_password_3"}
]

Replace your_ssid1 and your_password_1 with the first SSID and password combination, and so on. You can add as many combinations as you need, or only have one or two.

Save it on your Raspberry Pi Pico with the name: wifi_credentials.json. In Thonny IDE, go to File > Save as… > Raspberry Pi Pico. Call it wifi_credentials.json.

RPi-Pico-Saving-JSON-file-with-Wi-Fi-credentials

Connecting to Your Network Using the JSON File

With just a few modifications to the previous example, we can use that JSON file to try the different SSID and password combinations. Here’s the modified code:

# Rui Santos & Sara Santos - Random Nerd Tutorials
# Complete project details: https://RandomNerdTutorials.com/raspberry-pi-pico-w-save-network-credentials/

import network
import socket
import time
import json

# HTML template for the webpage
webpage = """
        <!DOCTYPE html>
        <html>
        <head>
            <title>Pico Web Server</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
        </head>
        <body>
            <h1>Raspberry Pi Pico Web Server</h1>
            <p>Hello, World!</p>
        </body>
        </html>
        """

def init_wifi_from_file(file_path='wifi_credentials.json'):
    try:
        with open(file_path, 'r') as file:
            credentials = json.load(file)
    except OSError:
        print(f"Error: Unable to read {file_path}. Make sure the file exists and is properly formatted.")
        return False

    for cred in credentials:
        ssid = cred.get('ssid')
        password = cred.get('password')
        if ssid and password:
            if init_wifi(ssid, password):
                return True

    print("Unable to connect to any Wi-Fi network.")
    return False

# Init Wi-Fi Interface
def init_wifi(ssid, password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.disconnect()

    print(f"Trying to connect to Wi-Fi network with SSID: {ssid}")

    wlan.connect(ssid, password)

    # Wait for Wi-Fi connection
    connection_timeout = 10
    while connection_timeout > 0:
        if wlan.isconnected():
            print('Connection successful!')
            network_info = wlan.ifconfig()
            print('IP address:', network_info[0])
            return True

        connection_timeout -= 1
        print('Waiting for Wi-Fi connection...')
        time.sleep(1)

    print(f"Failed to connect to Wi-Fi network with SSID: {ssid}")
    return False

# Set up Wi-Fi
if not init_wifi_from_file():
    print("Exiting program.")
else:
    try:
        # Set up socket and start listening
        addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
        s = socket.socket()
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(addr)
        s.listen()
        print('Listening on', addr)

        # Main loop to listen for connections
        while True:
            try:
                conn, addr = s.accept()
                print('Got a connection from', addr)

                # Receive and parse the request
                request = conn.recv(1024)
                request_str = request.decode('utf-8')
                print('Request content:')
                
                # Split headers and body
                headers, body = request_str.split('\r\n\r\n', 1)
                print('Headers:\n', headers)
                print('Body:\n', body)

                # Generate HTML response
                response = webpage

                # Send the HTTP response and close the connection
                conn.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
                conn.send(response)
                conn.close()

            except OSError as e:
                conn.close()
                print('Connection closed')

    except KeyboardInterrupt:
        print('Server stopped by user.')

View raw code

How the Code Works

Let’s just take a quick look at the relevant parts for this example.

We create a new function that will initialize Wi-Fi with the credentials saved in the JSON file.

def init_wifi_from_file(file_path='wifi_credentials.json'):
    try:
        with open(file_path, 'r') as file:
            credentials = json.load(file)
    except OSError:
        print(f"Error: Unable to read {file_path}. Make sure the file exists
                   and is properly formatted.")
        return False
    for cred in credentials:
        ssid = cred.get('ssid')
        password = cred.get('password')
        if ssid and password:
            if init_wifi(ssid, password):
                return True
    print("Unable to connect to any Wi-Fi network.")
    return False

It opens the file and saves the JSON content to the credentials variable.

with open(file_path, 'r') as file:
    credentials = json.load(file)

Then, we go through all JSON elements, and for each SSID/password combination, we attempt to connect to Wi-Fi:

for cred in credentials:
    ssid = cred.get('ssid')
    password = cred.get('password')
    if ssid and password:
        if init_wifi(ssid, password):
            return True

Then, before proceeding with the web server, we check if we are able to connect to any of the Wi-Fi networks. If we don’t, it will exit the program.

# Set up Wi-Fi
if not init_wifi_from_file():
    print("Exiting program.")

Otherwise, it will proceed with the rest of the code to create the web server.

Testing the Example

Run this previous example on your board. It will attempt to connect to your network using each SSID and password combination until it gets a connection.

In my case, to test this example, I purposedly only entered the right credentials in the second option. You can see that it attempts several times to connect using the firt SSID/password pair. It fails, so it will try the second option.

Raspberry Pi Pico Trying to Connect to Different Networks

With this second option, it will successfully connect to the network. This approach can be useful if you’re working on your project on different places with different networks.

Wrapping Up

In this quick example, we’ve shown you how to load the Wi-Fi credentials from a separate file. This can be useful because you don’t need to type your credentials in each code you want to test, and it prevents sharing your network credentials accidentally.

If you want your Raspberry Pi Pico to try more than one combination of SSID/password, you can create a JSON file with multiple combinations.

When creating web server projects or any networking projects, choose the method that is more suitable for your application.

We hope you’ve found this quick guide useful. We have more tutorials related to Wi-Fi with the Raspberry Pi Pico that you may like:

Learn more about the Raspberry Pi Pico with our resources:



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!

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.