wlan.rst 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. WLAN step by step
  2. =================
  3. The WLAN is a system feature of the WiPy, therefore it is always enabled
  4. (even while in ``machine.SLEEP``), except when deepsleep mode is entered.
  5. In order to retrieve the current WLAN instance, do::
  6. >>> from network import WLAN
  7. >>> wlan = WLAN() # we call the constructor without params
  8. You can check the current mode (which is always ``WLAN.AP`` after power up)::
  9. >>> wlan.mode()
  10. .. warning::
  11. When you change the WLAN mode following the instructions below, your WLAN
  12. connection to the WiPy will be broken. This means you will not be able
  13. to run these commands interactively over the WLAN.
  14. There are two ways around this::
  15. 1. put this setup code into your :ref:`boot.py file<wipy_filesystem>` so that it gets executed automatically after reset.
  16. 2. :ref:`duplicate the REPL on UART <wipy_uart>`, so that you can run commands via USB.
  17. Connecting to your home router
  18. ------------------------------
  19. The WLAN network card always boots in ``WLAN.AP`` mode, so we must first configure
  20. it as a station::
  21. from network import WLAN
  22. wlan = WLAN(mode=WLAN.STA)
  23. Now you can proceed to scan for networks::
  24. nets = wlan.scan()
  25. for net in nets:
  26. if net.ssid == 'mywifi':
  27. print('Network found!')
  28. wlan.connect(net.ssid, auth=(net.sec, 'mywifikey'), timeout=5000)
  29. while not wlan.isconnected():
  30. machine.idle() # save power while waiting
  31. print('WLAN connection succeeded!')
  32. break
  33. Assigning a static IP address when booting
  34. ------------------------------------------
  35. If you want your WiPy to connect to your home router after boot-up, and with a fixed
  36. IP address so that you can access it via telnet or FTP, use the following script as /flash/boot.py::
  37. import machine
  38. from network import WLAN
  39. wlan = WLAN() # get current object, without changing the mode
  40. if machine.reset_cause() != machine.SOFT_RESET:
  41. wlan.init(WLAN.STA)
  42. # configuration below MUST match your home router settings!!
  43. wlan.ifconfig(config=('192.168.178.107', '255.255.255.0', '192.168.178.1', '8.8.8.8'))
  44. if not wlan.isconnected():
  45. # change the line below to match your network ssid, security and password
  46. wlan.connect('mywifi', auth=(WLAN.WPA2, 'mywifikey'), timeout=5000)
  47. while not wlan.isconnected():
  48. machine.idle() # save power while waiting
  49. .. note::
  50. Notice how we check for the reset cause and the connection status, this is crucial in order
  51. to be able to soft reset the WiPy during a telnet session without breaking the connection.