Robust WiFi Connection Script for an ESP8266 in Micropython

Nathan Wells
2 min readSep 4, 2019
Image Credit: Vowstar [CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0)]

When I started programming in Micropython on a ESP8266 one of the main issues I kept having was wireless connection issues. I spent hours trouble-shooting issues only to have the problems resolve themselves (in a seemingly random mannor).

What I found out is that the ESP8266 stores previsouly connected WiFi networks in memory and tries to re-connect on boot. But in my experience, the success of this was spotty at best, especially if I was changing locations and needing to connect to a new WiFi network.

So I ended up writing a script that continues to retry to connect to a previously known network, but also will force the ESP8266 to connect to a network in a list if the connection fails.

I thought I would throw the code up here in case anyone else is interested in using it:

import network
import time
#Keep a list of various WiFi networks you would like to be able to connect to
#ex. "SSID": "PASSWORD",
dict_of_wifi = {
"SSID1": "PASSWORD1",
"SSID2": "PASSWORD2",
"SSID3": "PASSWORD3"
}
#Function to connect to WiFi - with 10 retries
def do_connect():
wlan = network.WLAN(network.STA_IF)
if not wlan.active():
wlan.active(True)
i = 1
if not wlan.isconnected():
for _ in range(10):
print('connecting to network...' + str(i))
#if not a new connection, just use cache
wlan.connect()
time.sleep(30)
#If we are having trouble connecting (fifth try)
#check available WiFi and try to connect
#to WiFi specified in dict_of_wifi if available
if not wlan.isconnected() and i == 5:
ssid = wlan.scan()
for x in ssid:
for wifi_ssid in dict_of_wifi:
if wifi_ssid in str(x):
wlan.connect(wifi_ssid, dict_of_wifi[wifi_ssid])
print('Trying ' + str(wifi_ssid))
time.sleep(30)
break
else:
pass
i += 1
if wlan.isconnected():
print('Connected.')
break
time.sleep(30)
else:
print('Fail')
print('network config:', wlan.ifconfig())
try:
#This loops forever, so adjust this to your own needs
while True:
#Connect to WiFi
wlan = network.WLAN(network.STA_IF)
#If we aren't connected to WiFi, then connect
if not wlan.isconnected():
print("not connected to WiFi...")
do_connect()
#Wait after connecting to WiFi
time.sleep(5)
#Then put your code here:
#....
#....
#Check WiFi connection every 15 min (will loop and check the connection)
time.sleep(900)
except Exception as e:
text = str(e)
print("There was a problem")
print(text)
#If there is an error, I like to reboot my ESP8266,
#so I do that here
time.sleep(30)
machine.reset()

You can place this code in your main.py or in any other script you want.

Would love to hear your thoughts and/or improvements!

If you enjoyed this article, please clap n number of times and share it!

--

--