Search code examples
wifimicrocontrolleresp32micropython

Esp32 wlan connection with micropython doesnt work


im trying to connect my esp32 microcontroller via wifi. But it doesnt work. I followed the tutorial on https://docs.micropython.org/en/latest/esp32/quickref.html#networking step by step and watched a lot of youtubevideos.

my code looks like this:

import network


wlan = network.WLAN(network.STA_IF) # create station interface
wlan.active(True)       
print(wlan.scan())
wlan.connect('my_wlan_ssid', 'my_wlan_password')
print(wlan.isconnected())
print("Wlan is connected: ", wlan.isconnected())
print("My Wlan config: ", wlan.ifconfig())

here i add a picture from my command linde from the Thonny editor Command line from Thonny editor

The funny thing is, the webinterface from my router shows me the connection to the esp32 controller with his ip-address. I also tried it with a mobile-hotspot from my mobilephone. My mobilephone shows me the connection with the esp32, but the esp32 doesn't recognize the wlan connection So why is it so? Do i something wrong?


Solution

  • Seems like you are not letting the network actually make the connection.

    wlan.connect('my_wlan_ssid', 'my_wlan_password')
    

    takes time and as shown in the linked reference, wlan.isconnected() should be called in a while loop to ensure that it exits only if it is connected. (you could of-course do better management)

    So how about you do this:

    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())
    

    As per your own link