Skip to content

Instantly share code, notes, and snippets.

@ShenTengTu
Last active September 17, 2023 11:43
Show Gist options
  • Save ShenTengTu/fde8d9231c9543cc72ba872c7db8d15a to your computer and use it in GitHub Desktop.
Save ShenTengTu/fde8d9231c9543cc72ba872c7db8d15a to your computer and use it in GitHub Desktop.
MicroPython : callback if connect network successful
import network
import time
SSID = ''
PASSWORD = ''
# disable all network interface first
network.WLAN(network.AP_IF).active(False)
network.WLAN(network.STA_IF).active(False)
def connect_network(ssid, password, on_successful=lambda:print('connect successful')):
# start connect
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, password)
# try to connecting
timeout = 10000
start = time.ticks_ms()
while sta_if.status() == network.STAT_CONNECTING:
diff = time.ticks_diff(time.ticks_ms(), start)
if diff > timeout:
print('Connecting Timeout')
break
print('\rconnecting %s' % diff, end="\r")
time.sleep_ms(1000)
# maybe connect successful, maybe not
if sta_if.isconnected():
if callable(on_successful):
on_successful() # do something
sta_if.disconnect()
else:
print('connect failed')
# wait disconnect complete
while sta_if.isconnected():
time.sleep_ms(100)
sta_if.active(False)
# connect_network(SSID, PASSWORD, on_successful_callback)
connect_network(SSID, PASSWORD)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment