Saturday, March 25, 2023

Micropython on ESP8266 - WLAN/DHCP setup and common issues

First, the minimal example that shall work with most hotspots you create on your mobile phone:

import network
 
# configure your hotspot like this or change this
WIFI_SSID = 'mySSID'
WIFI_PASSWORD = 'myWIFIPASSWORD'

# start the wlan
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID , WIFI_PASSWORD)

# test if the wlan is connected
wlan.isconnected()

If everything works fine, sooner or later the test will return true.

If not, continue here (for firmware version esp8266-20220618-v1.19.1.bin):

# print debugging information
import esp
esp.osdebug(0)

Then reconnect again and watch  the logs.

wlan.connect(WIFI_SSID , WIFI_PASSWORD)

In my case it was like this:

>>> sl
scandone
usl
 
This is not one of the common errors like 'wrong password' or something I could find at google. But maybe it can help in your case.

Besides the test if the wlan is connected there's also a command to check the status of the wlan, that I executed next:

wlan.status()

In my case it returned 1, equal to 'STAT_CONNECTING'. My WLAN router showed the device, along with a note 'The device doesn't need an IP address'. For me, DHCP didn't work, and to make it work I first configured a static IP address on the device, then connected to the WLAN and then configured my WLAN router to always assign a static address to my ESP8266. The last step is optional, though.
For the next example my WLAN router is configured with the IP address 192.168.1.1, the netmask 255.255.255.0 and the address 192.168.1.123 is a free address in my network.

# preparation
wlan.active(False)
wlan.active(True)

# set a static IP address
wlan.ifconfig(('192.168.1.123', '255.255.255.0', '192.168.1.1', '8.8.8.8'))

# start the wlan
wlan.connect(WIFI_SSID , WIFI_PASSWORD)

# test if the wlan is connected
wlan.isconnected()

The ESP8266 is now connected to my WLAN router. And after a reboot it would connect again, and DHCP would magically work.


No comments:

Post a Comment