Skip to content

Instantly share code, notes, and snippets.

@dybber
Last active July 29, 2024 03:29
Show Gist options
  • Save dybber/e2a137c65e7714be2c2ebcc255e95e3d to your computer and use it in GitHub Desktop.
Save dybber/e2a137c65e7714be2c2ebcc255e95e3d to your computer and use it in GitHub Desktop.
MicroPython wifi connection w. timeout
import machine
import time
import network
import urequests
# Function to connect to a specific wifi network
def connectToWifi(wifi, essid, password, timeout):
if not wifi.isconnected():
print("Connecting to WiFi network...")
wifi.connect(essid, password)
# Wait until connected
t = time.ticks_ms()
while not wifi.isconnected():
if time.ticks_diff(time.ticks_ms(), t) > timeout:
wifi.disconnect()
print("Timeout. Could not connect.")
return False
print("Successfully connected to " + essid)
return True
else:
print("Already connected")
return True
@dybber
Copy link
Author

dybber commented Sep 5, 2022

If you change line 10, it will not connect, and thus the while-loop will only stop when the timeout runs out and it gives up.

It works by attempting to call wifi.connect(...), then waiting for a while (determined by the timeout parameter), if the time passes and it hasn't connected it will time out and call wifi.disconnect()

This was written as part of an educational initiative, and is not at all production level code, and shouldn't be used for anything but small non-important projects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment