Search code examples
wifimicropython

First WiFi connection in MicroPython fails on RP2040


I'm running MicroPython on my Raspberry Pi Pico and trying to connect it to my WiFi with the following code:

wifi = network.WLAN(network.STA_IF)
wifi.active(True)
print(wifi.isconnected())
wifi.connect('<<SSID>>', '<<Password>>')
print(wifi.isconnected())

When running this for the very first time after plugging the Raspi into my laptop, it fails:

False
False

When running it the next time, it succeeds for the first call of isconnected():

True
True

So I tried a loop like this:

wifi = network.WLAN(network.STA_IF)
wifi.active(True)
while not wifi.isconnected():
    print('WiFi not connected, trying to connect')
    wifi.connect('<<SSID>>', '<<Password>>')
    time.sleep(1)

But with this, I'm running into an infinite loop and the WiFi never succeeds. When checking my router, the Raspi seems to be properly connected.


Solution

  • It seems to be a timing issue, the following code is stable and works properly:

    pin = Pin("LED", Pin.OUT)
    pin.off()
    
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    time.sleep(2)
    wifi.connect('<<SSID>>', '<<Password>>')
    time.sleep(2)
    
    max_wait = 10
    while max_wait > 0:
        if wifi.status() < 0 or wifi.status() >= 3:
            break
        max_wait -= 1
        time.sleep(1)
    
    if wifi.status() != 3:
        pin.on()
        raise RuntimeError('network connection failed')
    else:
        pin.on()
        time.sleep(1)
        pin.off()