As the title says... Chat on...

User avatar
By laurentp
#32056 Hi guys, nice work with NodeMCU/ESP.
I am rather experienced AVR/gcc (Atmel) hobbyist programmer, but totally new to LUA / NodeMCU.

I have tried to build a module of program, for the "beginning" of execution of bigger program:
- I want to ensure that NodeMCU is connected over WiFi, and has an IP address.

But program doesn't work, it hangs if is started so soon, that there is no WiFi/IP connection.
1). What is wrong?
2). How should it be done?
3). Where/what to read how it is organized (nodeMCU "ecosystem")?
4). Maybe should I use another "platform"?

I attach the code:
Code: Select all-- setup fast flashing LED- at the beginning don't
-- have IP etc
gpio.mode(0, gpio.OUTPUT)
-- timer 0, 100ms, repeat
function switch_gpio()
                  if gpio.read(0) == 1 then
                      gpio.write(0, gpio.LOW)
                  else
                      gpio.write(0, gpio.HIGH)
                  end
end

tmr.alarm(1, 100, 1, switch_gpio)

l_c = 0
l_c2 = 0

repeat
    while wifi.sta.status() ~= 5 do
            tmr.delay(1000000)
            l_c2 = l_c2 +1
            if l_c2 == 10 then
                l_c2 = 0
                wifi.sta.disconnect()
                tmr.delay(100000)
                wifi.sta.connect()
            end
    end   
   
    ip_addr, mask, gateway_addr=wifi.sta.getip()
   
    if ip_addr ~= nil then
        tmr.stop(1)
        gpio.write(0, gpio.HIGH)
        l_c = 1
    else
    tmr.delay(500000)
    end
until l_c == 1
User avatar
By dnc40085
#32427 Hello,
The problem is in the use of the function "tmr.delay()" which uses a non-SDK function "ets_delay_us()" to achieve it's goal and should only be used for IO timing more details HERE.

One way it could be done is by using the event monitor (wifi.sta.eventMonReg(), wifi.sta.eventMonStart(), wifi.sta.eventMonStop())
Code: Select all-- setup fast flashing LED- at the beginning don't
-- have IP etc
gpio.mode(0, gpio.OUTPUT)
-- timer 0, 100ms, repeat
function switch_gpio()
                  if gpio.read(0) == 1 then
                      gpio.write(0, gpio.LOW)
                  else
                      gpio.write(0, gpio.HIGH)
                  end
end

tmr.alarm(0, 100, 1, switch_gpio)

--Set callback for wifi event wifi.STA_FAIL
wifi.sta.eventMonReg(wifi.STA_FAIL, function()
    print("STATION_CONNECT_FAIL")
    wifi.sta.disconnect()
    tmr.alarm(1, 1000, 0, function() wifi.sta.connect() end)
end)

--Set callback for wifi event wifi.STA_GOTIP
wifi.sta.eventMonReg(wifi.STA_GOTIP, function()
    print("STATION_GOT_IP")
    ip_addr, mask, gateway_addr=wifi.sta.getip()
    print("\tIP: "..ip_addr.."\n\tNetmask: "..mask.."\n\tGateway: "..gateway_addr.."\n")
end)

--start wifi event monitor
wifi.sta.eventMonStart()