Bar
Bar

Reputation: 1

ESP32 WiFi connection VERY intermittent

I have an ESP-WROOM-32 and it's driving me crazy. I had it connecting to the WiFi network just fine but it won't connect any more. I have not made any changes or updated anything yet suddenly it gives this error:


Setup start connecting to "my network"" Traceback (most recent call last): File "", line 22, in NameError: name 'sta_if' isn't defined


I was plagued with this exact same error when I first tried to set it up but it just seemed to go away on it's own and worked fine for a while. `

import time
import network

ssidRouter = 'my network'                           #Router name
passwordRouter = 'my password'                         #Router passsword

def STA_Setup(ssidRouter,passwordRouter):
    print("Setup start")
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('connecting to',ssidRouter)
        sta_if.active(True)
        sta_if.connect(ssidRouter,passwordRouter)
        while not sta_if.isconnected():
            pass
    print('Connected, IP address:', sta_if.ifconfig())
    print("Setup End")

try:
    STA_Setup(ssidRouter,passwordRouter)
except:
    sta_if.disconnect()
    
    

` Does anyone have any idea what might be causing this behaviour?

I've tried resetting it, cycling power to it, rebooting my computer, different USB cable to ensure un-corrupted uploads, deleting and re-uploading the code, using an additional power source, screaming profanities at it, talking nicely to it...

Upvotes: 0

Views: 683

Answers (1)

Dave H.
Dave H.

Reputation: 628

sta_if is declared inside your STA_Setup() function. You are trying to access it outside of the function and that is why you're getting an error.

You can probably simplify things by getting rid of the Try/Except. If you want to show an error on connection timeout, something like this should work:

from network import WLAN, STA_IF
from time import ticks_ms

AP_NAME = 'myAP'
AP_PASS = 'abc123'
WIFI_TIMEOUT = 60

print('Connecting...')
wlan = WLAN(STA_IF)
wlan.active(True)
wlan.connect(AP_NAME, AP_PASS)
start_time = ticks_ms()
while not wlan.isconnected():
    if (ticks_ms() - start_time > WIFI_TIMEOUT * 1000):
        break
if (wlan.isconnected()):
    print('Connected')
else:
    print('Timeout!')

Instead of just pass in the while loop, you're now counting seconds. If the connection doesn't happen within the allotted time, the loop is exited. A final check of the connection let's you know if it was successful or not.

Upvotes: 1

Related Questions