Connect to a network
network_connect.py
##################################################################################
import network # mqtt needs network connection #
import time # to create small delays #
##################################################################################
##################################################################################
def wifi_connect(ssid, password):
##################################################################################
# get a "station interface" (opposed to access point interface) from the
# netwrok library. This object has the magic methods to connect to the
# wireless network and then to the LAN on the IP level.
sta_if = network.WLAN( network.STA_IF )
# If it is already active de-activate it first so that we always start
# from the same base state.
if sta_if.active():
sta_if.active(False)
# Now try to connect to the WIFI
sta_if.active( True ) # necessary to activate the interface.
print( "Connecting...")
sta_if.connect( ssid, password )
# Poll to know when the connection succeeds
connected = sta_if.isconnected()
# create some dotted lines on the display to
# indicate the process which takes time.
while not connected:
print( ".", end="")
time.sleep(0.1) # this is 100ms
connected = sta_if.isconnected()
print()
# If we arrive here we should be connected
print( "Success !")
mac = sta_if.config('mac')
# Show the IP address we got from the DHCP server
ifparm = sta_if.ifconfig()
iptxt = "IP:%s" % ifparm[0]
print( "We got the IP : %s" % ifparm[0] )
##################################################################################
#### test the routine above ###
wifi_connect( "student12", "$unilab1" )
print( "Success !!!")