Skip to content

Instantly share code, notes, and snippets.

@adammelancon
Created July 13, 2023 21:32
Show Gist options
  • Save adammelancon/2110036c42d19c17450d437629ef10e5 to your computer and use it in GitHub Desktop.
Save adammelancon/2110036c42d19c17450d437629ef10e5 to your computer and use it in GitHub Desktop.
A micropython file I drop on microcontrollers to attempt to connect to more than one wifi network.
import network
import time
# List of Wi-Fi SSIDs to try along with passwords.
ssid_list = ['wifi1', 'wifi2']
#If possible, put passwords in a config_secrets.py file.
password_list = ['wifipw1', 'wifipw2']
# password_list = ['wifipw1', ''] # If one is open wifi network.
def connect_to_wifi(ssid, password):
'''
takes an ssid/password combo and attempts to connect to wireless
'''
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
print(f'Attempting connection to "{ssid}"...')
for _ in range(10): # Try to connect for 10 seconds
if station.isconnected():
print(f"Connected to {ssid}.")
print("")
return True
time.sleep(1)
else:
print('Failed to connect to', ssid)
station.disconnect()
station.active(False)
return False
def attempt_wifi_networks():
'''
Loops through a list of ssid/password combos and passes it off to connect.
This allows me to have multiple ssid/passwords in my script
'''
for i in range(len(ssid_list)):
ssid = ssid_list[i]
password = password_list[i]
if connect_to_wifi(ssid, password):
return True
else:
print('No Wi-Fi networks available')
return False
attempt_wifi_networks()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment