Last active
October 24, 2016 21:50
-
-
Save marcelstoer/63ce6e6d78cef435d2ec to your computer and use it in GitHub Desktop.
Keep NodeMCU connected to WiFi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 |
I set:
WIFI_ALARM_ID = 10
WIFI_LED_BLINK_ALARM_ID = 11
WIFI_LED = 0
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
When I run the code I get: