wifi.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import network
  2. import utime
  3. def wifi_connect(essid, password):
  4. # Connect to the wifi. Based on the example in the micropython
  5. # documentation.
  6. wlan = network.WLAN(network.STA_IF)
  7. wlan.active(True)
  8. if not wlan.isconnected():
  9. print('connecting to network ' + essid + '...')
  10. wlan.connect(essid, password)
  11. # connect() appears to be async - waiting for it to complete
  12. while not wlan.isconnected():
  13. print('waiting for connection...')
  14. utime.sleep(4)
  15. print('checking connection...')
  16. print('Wifi connect successful, network config: %s' % repr(wlan.ifconfig()))
  17. else:
  18. # Note that connection info is stored in non-volatile memory. If
  19. # you are connected to the wrong network, do an explicity disconnect()
  20. # and then reconnect.
  21. print('Wifi already connected, network config: %s' % repr(wlan.ifconfig()))
  22. def wifi_disconnect():
  23. # Disconnect from the current network. You may have to
  24. # do this explicitly if you switch networks, as the params are stored
  25. # in non-volatile memory.
  26. wlan = network.WLAN(network.STA_IF)
  27. if wlan.isconnected():
  28. print("Disconnecting...")
  29. wlan.disconnect()
  30. else:
  31. print("Wifi not connected.")
  32. def disable_wifi_ap():
  33. # Disable the built-in access point.
  34. wlan = network.WLAN(network.AP_IF)
  35. wlan.active(False)
  36. print('Disabled access point, network status is %s' %
  37. wlan.status())