Skip to content

Instantly share code, notes, and snippets.

@confile
Created November 25, 2015 09:18
Show Gist options
  • Save confile/e9b794008a990482d789 to your computer and use it in GitHub Desktop.
Save confile/e9b794008a990482d789 to your computer and use it in GitHub Desktop.
Connect to WiFi
-- init.lua --
WIFI_SSID = "fill out"
WIFI_PASS = "fill out"
wifiReady = 0
WIFI_LED = 0
WIFI_ALARM_ID = 0
WIFI_LED_BLINK_ALARM_ID = 1
gpio.write(0, gpio.LOW)
function configureWiFi()
print("Startup up wifi mode")
wifi.setmode(wifi.STATION)
wifi.sta.config(WIFI_SSID, WIFI_PASS)
wifi.sta.autoconnect(1)
wifi.sta.connect()
tmr.alarm(WIFI_ALARM_ID, 2000, 1, wifi_watch)
end
function run()
print("run")
print(wifi.sta.getip())
-- Run the main file
--dofile("main.lua")
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
print("WiFi: connected")
print(wifi.sta.getip())
turnWiFiLedOff()
if (wifiReady == 0) then
wifiReady = 1
run()
end
else
print("WiFi: (re-)connecting")
wifiReady = 0
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.LOW)
end
function turnWiFiLedOff()
gpio.write(WIFI_LED, gpio.HIGH)
end
configureWiFi()
@devsaurus
Copy link

Your script works for me if I uncomment line 59. The ESP need probably more than 2 seconds to connect and the subsequent wifi.sta.connect() re-triggers this process.

A different approach for init.lua is wifi.sta.eventMonReg(). It's an elegant way to trigger activity once an IP was assigned:

wifi.sta.eventMonReg(wifi.STA_GOTIP,
    function()
        print("Got IP, starting...")
        wifi.sta.eventMonStop("unreg all")
        local s,err
        local basename = "main_script"
        if file.open(basename..".lc") then
            file.close()
            s,err = pcall(function() dofile(basename..".lc") end)
        else
            s,err = pcall(function() dofile(basename..".lua") end)
        end
        if not s then print(err) end
    end
)

wifi.sta.eventMonStart()

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