{"id":102447,"date":"2021-04-14T15:38:16","date_gmt":"2021-04-14T15:38:16","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=102447"},"modified":"2021-04-14T15:50:03","modified_gmt":"2021-04-14T15:50:03","slug":"solved-reconnect-esp8266-nodemcu-to-wifi","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/solved-reconnect-esp8266-nodemcu-to-wifi\/","title":{"rendered":"[SOLVED] Reconnect ESP8266 NodeMCU to Wi-Fi Network After Lost Connection"},"content":{"rendered":"\n<p>This quick guide shows different ways to reconnect the ESP8266 NodeMCU board to a Wi-Fi network after a lost connection. This can be useful if the ESP8266 temporarily loses the Wi-Fi signal; the ESP8266 is temporarily out of the router&#8217;s Wi-Fi range; the router restarts; the router loses internet connection or other situations.<\/p>\n\n\n\n<div class=\"wp-block-image is-style-default\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/03\/ESP8266-Reconnect-to-WiFi-After-Lost-Connection.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Resolved ESP8266 NodeMCU Reconnect to Wi-Fi After Connection is Lost\" class=\"wp-image-102468\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/03\/ESP8266-Reconnect-to-WiFi-After-Lost-Connection.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/03\/ESP8266-Reconnect-to-WiFi-After-Lost-Connection.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/03\/ESP8266-Reconnect-to-WiFi-After-Lost-Connection.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/03\/ESP8266-Reconnect-to-WiFi-After-Lost-Connection.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n\n<p>We have a similar guide for the ESP32 board:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/solved-reconnect-esp32-to-wifi\/\">[SOLVED] Reconnect ESP32 to Wi-Fi Network After Lost Connection<\/a><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"9\">Reconnect to Wi-Fi Network After Lost Connection<\/h2>\n\n\n\n<p>The ESP8266 has the ability to automatically reconnect to your router in case of a Wi-Fi outage. For example, if the ESP8266 is connected to your router and you suddenly turn it off, when it goes back on, the ESP8266 can reconnect automatically. However, many of our readers report situations in which the ESP8266 doesn&#8217;t reconnect. In those cases, you can try one of the other next suggestions (continue reading).<\/p>\n\n\n\n<p>To reconnect to Wi-Fi after a connection is lost, you can use <span class=\"rnthl rntliteral\">WiFi.setAutoReconnect(true);<\/span> followed by <span class=\"rnthl rntliteral\"> WiFi.persistent(true);<\/span> to automatically reconnect to the previously connected access point:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>WiFi.setAutoReconnect(true);\nWiFi.persistent(true);<\/code><\/pre>\n\n\n\n<p>Add these previous lines right after connecting to your Wi-Fi network. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void initWiFi() {\n  WiFi.mode(WIFI_STA);\n  WiFi.begin(ssid, password);\n  Serial.print(\"Connecting to WiFi ..\");\n  while (WiFi.status() != WL_CONNECTED) {\n    Serial.print('.');\n    delay(1000);\n  }\n  Serial.println(WiFi.localIP());\n  WiFi.setAutoReconnect(true);\n  WiFi.persistent(true);\n}<\/code><\/pre>\n\n\n\n<p>Here&#8217;s a complete example using this method. Every 30 seconds, it prints the Wi-Fi connection status. You can temporarily shut down your router and see the wi-fi status changing. When the router is back on again, it should automatically connect.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*\n  Rui Santos\n  Complete project details at https:\/\/RandomNerdTutorials.com\/solved-reconnect-esp8266-nodemcu-to-wifi\/\n  \n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files.\n  \n  The above copyright notice and this permission notice shall be included in all\n  copies or substantial portions of the Software.\n*\/\n\n#include &lt;ESP8266WiFi.h&gt;\n\n\/\/ Replace with your network credentials\nconst char* ssid = &quot;REPLACE_WITH_YOUR_SSID&quot;;\nconst char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;\n\nunsigned long previousMillis = 0;\nunsigned long interval = 30000;\n\nvoid initWiFi() {\n  WiFi.mode(WIFI_STA);\n  WiFi.begin(ssid, password);\n  Serial.print(&quot;Connecting to WiFi ..&quot;);\n  while (WiFi.status() != WL_CONNECTED) {\n    Serial.print('.');\n    delay(1000);\n  }\n  Serial.println(WiFi.localIP());\n  \/\/The ESP8266 tries to reconnect automatically when the connection is lost\n  WiFi.setAutoReconnect(true);\n  WiFi.persistent(true);\n}\n\nvoid setup() {\n  Serial.begin(115200);\n  initWiFi();\n  Serial.print(&quot;RSSI: &quot;);\n  Serial.println(WiFi.RSSI());\n}\n\nvoid loop() {\n  \/\/print the Wi-Fi status every 30 seconds\n  unsigned long currentMillis = millis();\n  if (currentMillis - previousMillis &gt;=interval){\n    switch (WiFi.status()){\n      case WL_NO_SSID_AVAIL:\n        Serial.println(&quot;Configured SSID cannot be reached&quot;);\n        break;\n      case WL_CONNECTED:\n        Serial.println(&quot;Connection successfully established&quot;);\n        break;\n      case WL_CONNECT_FAILED:\n        Serial.println(&quot;Connection failed&quot;);\n        break;\n    }\n    Serial.printf(&quot;Connection status: %d\\n&quot;, WiFi.status());\n    Serial.print(&quot;RRSI: &quot;);\n    Serial.println(WiFi.RSSI());\n    previousMillis = currentMillis;\n  }\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP8266\/ESP8266_Auto_Reconnect.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>Another alternative is calling <span class=\"rnthl rntliteral\">WiFi.disconnect()<\/span> followed by <span class=\"rnthl rntliteral\">WiFi.begin(ssid,password)<\/span> when you notice that the connection was lost <span class=\"rnthl rntliteral\">(WiFi.status() != WL_CONNECTED)<\/span><\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>WiFi.disconnect();\nWiFi.begin(ssid, password);<\/code><\/pre>\n\n\n\n<p>Alternatively, you can also try to restart the ESP8266 with <span class=\"rnthl rntliteral\">ESP.restart()<\/span> when the connection is lost. <\/p>\n\n\n\n<p>You can add something like the snippet below to the <span class=\"rnthl rntliteral\">loop()<\/span> that checks once in a while if the board is connected and tries to reconnect if it has lost the connection.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>unsigned long currentMillis = millis();\n\/\/ if WiFi is down, try reconnecting\nif ((WiFi.status() != WL_CONNECTED) &amp;&amp; (currentMillis - previousMillis &gt;=interval)) {\n  Serial.print(millis());\n  Serial.println(\"Reconnecting to WiFi...\");\n  WiFi.disconnect();\n  WiFi.begin(YOUR_SSID, YOUR_PASSWORD);\n  previousMillis = currentMillis;\n}<\/code><\/pre>\n\n\n\n<p>Don&#8217;t forget to declare the <span class=\"rnthl rntliteral\">previousMillis<\/span> and <span class=\"rnthl rntliteral\">interval<\/span> variables. The <span class=\"rnthl rntliteral\">interval<\/span> corresponds to the period of time between each check in milliseconds (for example 30 seconds):<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>unsigned long previousMillis = 0;\nunsigned long interval = 30000;<\/code><\/pre>\n\n\n\n<p>Here&#8217;s a complete example.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*\n  Rui Santos\n  Complete project details at https:\/\/RandomNerdTutorials.com\/solved-reconnect-esp8266-nodemcu-to-wifi\/\n  \n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files.\n  \n  The above copyright notice and this permission notice shall be included in all\n  copies or substantial portions of the Software.\n*\/\n\n#include &lt;ESP8266WiFi.h&gt;\n\n\/\/ Replace with your network credentials\nconst char* ssid = &quot;REPLACE_WITH_YOUR_SSID&quot;;\nconst char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;\n\nunsigned long previousMillis = 0;\nunsigned long interval = 30000;\n\nvoid initWiFi() {\n  WiFi.mode(WIFI_STA);\n  WiFi.begin(ssid, password);\n  Serial.print(&quot;Connecting to WiFi ..&quot;);\n  while (WiFi.status() != WL_CONNECTED) {\n    Serial.print('.');\n    delay(1000);\n  }\n  Serial.println(WiFi.localIP());\n}\n\nvoid setup() {\n  Serial.begin(115200);\n  initWiFi();\n  Serial.print(&quot;RRSI: &quot;);\n  Serial.println(WiFi.RSSI());\n}\n\nvoid loop() {\n  unsigned long currentMillis = millis();\n  \/\/ if WiFi is down, try reconnecting every CHECK_WIFI_TIME seconds\n  if ((WiFi.status() != WL_CONNECTED) &amp;&amp; (currentMillis - previousMillis &gt;=interval)) {\n    Serial.print(millis());\n    Serial.println(&quot;Reconnecting to WiFi...&quot;);\n    WiFi.disconnect();\n    WiFi.begin(ssid, password);\n    Serial.println(WiFi.localIP());\n    \/\/Alternatively, you can restart your board\n    \/\/ESP.restart();\n    Serial.println(WiFi.RSSI());\n    previousMillis = currentMillis;\n  }\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP8266\/ESP8266_Reconnect_WiFi.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>This example shows how to connect to a network and checks every 30 seconds if it is still connected. If it isn&#8217;t, it disconnects and tries to reconnect again.<\/p>\n\n\n\n<p>There is also the <span class=\"rnthl rntliteral\">WiFi.reconnect()<\/span> function. However, after several tries, we couldn&#8217;t make it work. If anyone knows if there is any trick to make it work, please share.<\/p>\n\n\n\n<p>You can also use Wi-Fi Events to detect that the connection was lost and call a function to handle what to do when that happens (see the next section).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"10\">ESP8266 NodeMCU Wi-Fi Events<\/h2>\n\n\n\n<p>The ESP8266 is able to handle different Wi-Fi events. With Wi-Fi events, you don&#8217;t need to be constantly checking the Wi-Fi state. When a certain event happens, it automatically calls the corresponding handling function.<\/p>\n\n\n\n<p>The following events are very useful to detect if the connection was lost or reestablished:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><span class=\"rnthl rntliteral\">onStationModeGotIP<\/span>: when the ESP8266 gets to its final step of the connection: getting its network IP address;<\/li><li><span class=\"rnthl rntliteral\">onStationModeDisconnected<\/span>: when the ESP8266 is no longer connected to an access point.<\/li><\/ul>\n\n\n\n<p>Go to the next section to see an application example.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11\">Reconnect to Wi-Fi Network After Lost Connection (Wi-Fi Events)<\/h3>\n\n\n\n<p>Wi-Fi events can be useful to detect that a connection was lost and try to reconnect right after (use the <span class=\"rnthl rntliteral\">onStationModeDisconnected<\/span> event). Here&#8217;s a sample code:<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*\n  Rui Santos\n  Complete project details at https:\/\/RandomNerdTutorials.com\/solved-reconnect-esp8266-nodemcu-to-wifi\/\n  \n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files.\n  \n  The above copyright notice and this permission notice shall be included in all\n  copies or substantial portions of the Software.\n*\/\n\n#include &lt;ESP8266WiFi.h&gt;\n\n\/\/ Replace with your network credentials\nconst char* ssid = &quot;REPLACE_WITH_YOUR_SSID&quot;;\nconst char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;\n\nWiFiEventHandler wifiConnectHandler;\nWiFiEventHandler wifiDisconnectHandler;\n\nvoid initWiFi() {\n  WiFi.mode(WIFI_STA);\n  WiFi.begin(ssid, password);\n  Serial.print(&quot;Connecting to WiFi ..&quot;);\n  while (WiFi.status() != WL_CONNECTED) {\n    Serial.print('.');\n    delay(1000);\n  }\n  Serial.println(WiFi.localIP());\n}\n\nvoid onWifiConnect(const WiFiEventStationModeGotIP&amp; event) {\n  Serial.println(&quot;Connected to Wi-Fi sucessfully.&quot;);\n  Serial.print(&quot;IP address: &quot;);\n  Serial.println(WiFi.localIP());\n}\n\nvoid onWifiDisconnect(const WiFiEventStationModeDisconnected&amp; event) {\n  Serial.println(&quot;Disconnected from Wi-Fi, trying to connect...&quot;);\n  WiFi.disconnect();\n  WiFi.begin(ssid, password);\n}\n\nvoid setup() {\n  Serial.begin(115200);\n\n  \/\/Register event handlers\n  wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);\n  wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);\n   \n  initWiFi();\n  Serial.print(&quot;RRSI: &quot;);\n  Serial.println(WiFi.RSSI());\n}\n\nvoid loop() {\n  \/\/delay(1000);\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP8266\/ESP8266_Network_Events_CD.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">How it Works?<\/h4>\n\n\n\n<p>In this example, we&#8217;ve added two Wi-Fi events: when the ESP8266 connects and gets an IP address, and when it disconnects.<\/p>\n\n\n\n<p>When the ESP8266 station connects to the access point and gets it IP address (<span class=\"rnthl rntliteral\">onStationModeGotIP<\/span> event), the <span class=\"rnthl rntliteral\">onWifiConnect()<\/span> function will be called:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">onWifiConnect()<\/span> function simply prints that the ESP8266 connected to Wi-fi successfully and prints its local IP address. However, you can modify the function to do any other task (like light up an LED to indicate that it is successfully connected to the network).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onWifiConnect(const WiFiEventStationModeGotIP&amp; event) {\n  Serial.println(\"Connected to Wi-Fi sucessfully.\");\n  Serial.print(\"IP address: \");\n  Serial.println(WiFi.localIP());\n}<\/code><\/pre>\n\n\n\n<p>When the ESP8266 loses the connection with the access point (<span class=\"rnthl rntliteral\">onStationModeDisconnected<\/span> event), the <span class=\"rnthl rntliteral\">onWifiDisconnect()<\/span> function is called.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);<\/code><\/pre>\n\n\n\n<p>That function prints a message indicating that the connection was lost and tries to reconnect:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onWifiDisconnect(const WiFiEventStationModeDisconnected&amp; event) {\n  Serial.println(\"Disconnected from Wi-Fi, trying to connect...\");\n  WiFi.disconnect();\n  WiFi.begin(ssid, password);\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>This quick tutorial shows different ways on how you can reconnect your ESP8266 NodeMCU board to a Wi-Fi network after the connection is lost (if it doesn&#8217;t do that automatically).<\/p>\n\n\n\n<p>For more information about ESP8266 Wi-Fi functions, we recommend taking a look at the documentation: <\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/arduino-esp8266.readthedocs.io\/en\/latest\/esp8266wifi\/readme.html\" target=\"_blank\" rel=\"noreferrer noopener\">ESP8266WiFi library Documentation<\/a><\/li><li><a href=\"https:\/\/arduino-esp8266.readthedocs.io\/en\/latest\/esp8266wifi\/station-class.html\" target=\"_blank\" rel=\"noreferrer noopener\">ESP8266 Station Class<\/a><\/li><\/ul>\n\n\n\n<p>One of the best applications of the ESP8266 Wi-Fi capabilities is building web servers. If you want to use the ESP8266 NodeMCU or ESP32 boards to build Web Server projects, you might like our eBook:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><a href=\"https:\/\/randomnerdtutorials.com\/build-web-servers-esp32-esp8266-ebook\/\">Build Web Servers with the ESP32\/ESP8266 eBook&nbsp;(2nd edition)<\/a><\/strong><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/home-automation-using-esp8266\/\"><strong>Home Automation using ESP8266 eBook<\/strong><\/a><\/li><\/ul>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful.<\/p>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This quick guide shows different ways to reconnect the ESP8266 NodeMCU board to a Wi-Fi network after a lost connection. This can be useful if the ESP8266 temporarily loses the &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"[SOLVED] Reconnect ESP8266 NodeMCU to Wi-Fi Network After Lost Connection\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/solved-reconnect-esp8266-nodemcu-to-wifi\/#more-102447\" aria-label=\"Read more about [SOLVED] Reconnect ESP8266 NodeMCU to Wi-Fi Network After Lost Connection\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":102468,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[214,265,246,240,300,264],"tags":[],"class_list":["post-102447","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp8266","category-esp8266-project","category-esp8266-arduino-ide","category-esp8266-projects","category-0-esp8266","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/03\/ESP8266-Reconnect-to-WiFi-After-Lost-Connection.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/102447","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=102447"}],"version-history":[{"count":0,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/102447\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/102468"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=102447"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=102447"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=102447"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}