Skip to content

Instantly share code, notes, and snippets.

@marcelstoer
Last active October 24, 2016 21:50
Show Gist options
  • Save marcelstoer/63ce6e6d78cef435d2ec to your computer and use it in GitHub Desktop.
Save marcelstoer/63ce6e6d78cef435d2ec to your computer and use it in GitHub Desktop.
Keep NodeMCU connected to WiFi
-- If you have a recent firmware from the dev branch you could do away with that ugly timer
-- by relying on WiFi events and (re-)acting accordingly. See wifi.sta.eventMonReg() at
-- https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en#wifistaeventmonreg
-- init all globals
...
wifiReady = 0
function configureWiFi()
wifi.setmode(wifi.STATION)
wifi.sta.config(WIFI_SSID, WIFI_PASS)
wifi.sta.connect()
tmr.alarm(WIFI_ALARM_ID, 1000, 1, wifi_watch)
end
-- while NOT connected to WiFi you blink a LED, see below
function wifi_watch()
-- 0: STATION_IDLE,
-- 1: STATION_CONNECTING,
-- 2: STATION_WRONG_PASSWORD,
-- 3: STATION_NO_AP_FOUND,
-- 4: STATION_CONNECT_FAIL,
-- 5: STATION_GOT_IP.
status = wifi.sta.status()
if status == 5 then
-- only do something if the status actually changed
-- you could of course combine these two 'if's but it's more explicit for this gist
if wifiReady == 0 then
wifiReady = 1
print("WiFi: connected")
turnWiFiLedOn()
-- do something
end
else
wifiReady = 0
print("WiFi: (re-)connecting")
turnWiFiLedOnOff()
wifi.sta.connect()
end
end
function turnWiFiLedOnOff()
turnWiFiLedOn()
tmr.alarm(WIFI_LED_BLINK_ALARM_ID, 500, 0, function()
turnWiFiLedOff()
end)
end
function turnWiFiLedOn()
gpio.write(WIFI_LED, gpio.HIGH)
end
function turnWiFiLedOff()
gpio.write(WIFI_LED, gpio.LOW)
end
@confile
Copy link

confile commented Nov 6, 2015

When I run the code I get:

> configureWiFi()
stdin:6: tmr 10 does not exist
stack traceback:
    [C]: in function 'alarm'
    stdin:6: in function 'configureWiFi'
    stdin:1: in main chunk

@confile
Copy link

confile commented Nov 6, 2015

I set:

WIFI_ALARM_ID = 10
WIFI_LED_BLINK_ALARM_ID = 11
WIFI_LED = 0

@confile
Copy link

confile commented Nov 6, 2015

My fault wrong timer id. Thanks for your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment