IoT Bytes

Bits and Bytes of IoT

Checking WiFi Status Before Performing any Operation on ESP8266

Pradeep Singh | 25th April 2016wifi

Most of the tasks performed on ESP8266 would need network connectivity to publish or check some information to/from other network endpoints. After reboot or wakeup from deep sleep, ESP8266 can take from 4 to 10 seconds time to connect to WiFi Network. Considering these points it becomes really important to check the status of WiFi connection before initiating any dependent operation.

Here you have sample lua code written for ESP8266 running NodeMCU firmware. In this example “do_Something()” function will get executed once the Network connection comes up.

------------------------------------------
--- NodeMCU Firmware: nodemcu_float_0.9.6-dev_20150704.bin
------------------------------------------

-----------------------------------------------
--- Variables Block ---
-----------------------------------------------
--- WIFI CONFIGURATION ---
WIFI_SSID = "your WiFi SSID"
WIFI_PASSWORD = "your WiFi Password"

--- WiFi IP CONFIG (Leave blank to use DHCP) ---
ESP8266_IP=""
ESP8266_NETMASK=""
ESP8266_GATEWAY=""

--- Other Variables ---
STATUS_CHECK_INTERVAL = 1000
IS_WIFI_READY = 0
STATUS_CHECK_COUNTER = 0
STOP_AFTER_ATTEMPTS = 45

-----------------------------------------------


-----------------------------------------------
--- Code Block ---
-----------------------------------------------

--- Connect to the wifi network ---
wifi.setmode(wifi.STATION) 
wifi.sta.config(WIFI_SSID, WIFI_PASSWORD) 
wifi.sta.connect()

if ESP8266_IP ~= "" then
 wifi.sta.setip({ip=ESP8266_IP,netmask=ESP8266_NETMASK,gateway=ESP8266_GATEWAY})
end


--- Check WiFi Connection Status ---
function get_WiFi_Status()
 ip_Add = wifi.sta.getip()
 if ip_Add ~= nill then
 print('Connected with WiFi. IP Add: ' .. ip_Add)
 IS_WIFI_READY = 1
 tmr.stop(0)
--- Call some function ---
 do_Something()
 end
end


--- Replace this with your function ---
function do_Something()
 print ("yo!!!")
end


--- Check WiFi Status before starting anything ---
tmr.alarm(0, STATUS_CHECK_INTERVAL, 1, function() 
 
 get_WiFi_Status()
 tmr.delay(STATUS_CHECK_INTERVAL)

 --- Stop from getting into infinite loop ---
 STATUS_CHECK_COUNTER = STATUS_CHECK_COUNTER + 1
 if STOP_AFTER_ATTEMPTS == STATUS_CHECK_COUNTER then
 tmr.stop(0)
 print ("Unable to connect to WiFi. Please check settings...")
 end 
end)

-----------------------------------------------

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: