ESP8266 can act as both Station / WIFI client (STA_IF interface) and Access Point (AP_IF interface). AP_IF interface is active by default in MycroPython firmware on ESP826 . In the earlier post, we connected to the access point (AP mode) of ESP8266 and used WebREPL to remotely control switch on/off and brightness of an LED. Now, we'll configure the ESP8266 (as WIFI client) so that it connects to the WIFI router automatically after booting.

1. Prerequisite

This post is continuation of my earlier posts

  1. How to flash MicroPython firmware onto an ESP8266 ESP-12E chip using esptool?
  2. How to setup WebREPL to connect to Python prompt (REPL) of ESP8266 over WIFI network?
  3. Example: Remotely switch on/off and control brightness of an LED using MicroPython WebREPL

2. Connect to WebREPL

Connect your computer to the WIFI access point of ESP8266. Open webrepl.html using Chrome or Firefox browser and connect to WebREPL.

3. Connect to WIFI

a. Import network module and create a station interface using WLAN class.

import network
sta_if = network.WLAN(network.STA_IF)

b. Activate the STA_IF (Station / WIFI client) interface.

sta_if.active(True)

c. Connect to the desired wireless network, using corresponding SSID and password.

sta_if.connect('ssid', 'password')

d. Once connected, we can see network configurations (IP address, subnet mask, gateway and DNS server) using following command.

>>> sta_if.ifconfig()
('192.168.1.4', '255.255.255.0', '192.168.1.1', '192.168.1.1')

In my case '192.168.1.4' is the IP address of my ESP8266 WIFI client connected to my home network.

Sample Code:

Welcome to MicroPython!                                                             
Password:                                                                           
WebREPL connected                                                                   
>>>                                                                                 
paste mode; Ctrl-C to cancel, Ctrl-D to finish                                      
=== import network                                                                  
=== sta_if = network.WLAN(network.STA_IF)                                           
=== sta_if.active(True)                                                             
=== sta_if.connect('ssid', 'password')                                             
===                                                                                 
>>> sta_if.ifconfig()                                                               
('192.168.1.4', '255.255.255.0', '192.168.1.1', '192.168.1.1')                      
>>>

For better coding practice, we'll wrap all the above code statements in a function (e.g. connect) and call the same function whenever we need to connect to that WIFI router.

def connect():
     import network
     import time
 
     # Create Station interface
     sta_if = network.WLAN(network.STA_IF) 
        
     if not sta_if.isconnected():
          print('Connecting...')
 
          # Enable the interface
          sta_if.active(True)
 
          # Connect
          sta_if.connect('ssid', 'password')
 
          # Wait till connection is established
          while not sta_if.isconnected():
               time.sleep_ms(300)
 
          print('It is now connected.')
           
     else:
          print('Already Connected.')   
 
     print('Network Settings:', sta_if.ifconfig())

If you have multiple WIFI access points, you can make the above function parameterized and pass SSID & password value while making the call.

4. Verify

a. Note down the MAC address (e.g. 5c:cf:7f:d0:fa:00) of ESP8266

from network import WLAN
import ubinascii
 
#MAC address (bytes)
macAddress = WLAN().config('mac')
 
#Conver binary to ascii
binaryToAscii = ubinascii.hexlify(macAddress,':')
print(macAddress, '-->', binaryToAscii, '-->', binaryToAscii.decode())

b. Login to the wireless router admin and verify whether ESP8266 is connected to the router or not.

c. If the WIFI router is connected to Internet, then try to make a HTTP call. We'll get a JSON data over Internet.

import urequests
 
response = urequests.get("http://date.jsontest.com")                                   
response.json()
 
response.close()

5. Configure ESP8266 for automatic WIFI connection

It would be nice, if we can do something so that ESP8266 connects to the WIFI netwrok automatically after booting, instead of connecting it manually every time. Let?s make that happen.

a. Connect with ESP8266 using WebREPL.

b. Download boot.py file from ESP8266.

boot.py

# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
import gc
import webrepl
webrepl.start()
gc.collect()

c. Open boot.py in a text editor and append the connect() function definition followed by a function call at the end of boot.py.

# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
import gc
import webrepl
webrepl.start()
gc.collect()
 
def connect():
     import network
     import time
 
     # Create Station interface
     sta_if = network.WLAN(network.STA_IF) 
 
     if not sta_if.isconnected():
          print('Connecting...')
 
          # Enable the interface
          sta_if.active(True)
 
          # Connect
          sta_if.connect('ssid', 'password')
 
          # Wait till connection is established
          while not sta_if.isconnected():
               time.sleep_ms(300)
 
          print('It is now connected.')
 
     else:
          print('Already Connected.')   
 
     print('Network Settings:', sta_if.ifconfig())
 
connect()

d. Upload the modified boot.py to ESP8266.

e. To verify, you can reiterate steps 4b and 4c.

References