Connecting the MicroPython-powered NodeMCU to WiFi

Connect the NodeMCU to a Wireless Network

import network

##
## STA allows the esp8266 to act as a wireless client.
## AP allows the esp8266 to act as a wireless access point.
##
sta_if = network.WLAN(network.STA_IF)
ap_if  = network.WLAN(network.AP_IF)

## Check if the Network is currently active
sta_if.active()
ap_if.active()

## Check if the Network is currently configured
ap_if.ifconfig()
sta_if.ifconfig()

## Enable the Wifi Client
sta_if.active(True)

## Connect to the Wireless Network
sta_if.connect('ESSID', 'PASSWORD')

## Check if connected
sta_if.isconnected()

## Print IP address information
sta_if.ifconfig()

## Disable the Access Point
ap_if.active(False)

WebREPL

Configure and start WebREPL.

import webrepl
import webrepl_setup
webrepl.start()

Connect to the WebREPL

Place the network configuration in to the boot.py file

  • MicroPython has two startup scripts: boot.py and main.py.

  • boot.py is executed first, followed by main.py.

  • We will put our network configuration in to the boot.py to ensure it properly connects to the network on startup.

import gc
import webrepl
import network

sta_if = network.WLAN(network.STA_IF)

if not sta_if.isconnected():
  print('Connecting to Network...')
  sta_if.active(True)
  sta_if.connect('ESSID', 'PASSWORD')
  while not sta_if.isconnected():
    pass

print('Network Config: ', sta_if.ifconfig())

webrepl.start()
gc.collect()
categories: micropython | esp8266 | nodemcu |