{"id":101925,"date":"2021-02-11T15:05:38","date_gmt":"2021-02-11T15:05:38","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=101925"},"modified":"2022-10-27T10:51:55","modified_gmt":"2022-10-27T10:51:55","slug":"solved-reconnect-esp32-to-wifi","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/solved-reconnect-esp32-to-wifi\/","title":{"rendered":"[SOLVED] Reconnect ESP32 to Wi-Fi Network After Lost Connection"},"content":{"rendered":"\n<p>This quick guide shows how you can reconnect your ESP32 to a Wi-Fi network after losing the connection. This can be useful in the following scenarios: the ESP32 temporarily loses Wi-Fi signal; the ESP32 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<div class=\"wp-block-image is-style-default\">\n<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\/02\/ESP32-Reconnect-to-WiFi-After-Lost-Connection-Solved.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Reconnect to Wi-Fi After Lost Connection network\" class=\"wp-image-102002\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/ESP32-Reconnect-to-WiFi-After-Lost-Connection-Solved.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/ESP32-Reconnect-to-WiFi-After-Lost-Connection-Solved.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/ESP32-Reconnect-to-WiFi-After-Lost-Connection-Solved.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/ESP32-Reconnect-to-WiFi-After-Lost-Connection-Solved.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<p>We have a similar guide for the ESP8266 NodeMCU board:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/solved-reconnect-esp8266-nodemcu-to-wifi\/\">[SOLVED] Reconnect ESP8266 NodeMCU to Wi-Fi Network After Lost Connection<\/a><\/li><\/ul>\n\n\n\n<p>You may also want to take a look at <a href=\"https:\/\/randomnerdtutorials.com\/esp32-wifimulti\/\">WiFiMulti<\/a>. It allows you to register multiple networks (SSID\/password combinations). The ESP32 will connect to the Wi-Fi network with the strongest signal (RSSI). If the connection is lost, it will connect to the next network on the list. Read: <a href=\"https:\/\/randomnerdtutorials.com\/esp32-wifimulti\/\">ESP32 WiFiMulti: Connect to the Strongest Wi-Fi Network (from a list of networks)<\/a>.<\/p>\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>To reconnect to Wi-Fi after a connection is lost, you can use <span class=\"rnthl rntliteral\">WiFi.reconnect()<\/span> to try to reconnect to the previously connected access point:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>WiFi.reconnect()<\/code><\/pre>\n\n\n\n<p>Or, you can call <span class=\"rnthl rntliteral\">WiFi.disconnect()<\/span> followed by <span class=\"rnthl rntliteral\">WiFi.begin(ssid,password)<\/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 ESP32 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 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.reconnect();\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-esp32-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;WiFi.h&gt;\n\n\/\/ Replace with your network credentials (STATION)\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;RSSI: &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.reconnect();\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\/ESP32\/ESP32_Auto_Reconnect.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>Alternatively, 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\">ESP32 Wi-Fi Events<\/h2>\n\n\n\n<p>The ESP32 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\">ARDUINO_EVENT_WIFI_STA_CONNECTED<\/span>: the ESP32 is connected in station mode to an access point\/hotspot (your router);<\/li><li><span class=\"rnthl rntliteral\">ARDUINO_EVENT_WIFI_STA_DISCONNECTED<\/span>: the ESP32 station disconnected from the 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\">ARDUINO_EVENT_WIFI_STA_DISCONNECTED<\/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-esp32-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;WiFi.h&gt;\n \nconst char* ssid = &quot;REPLACE_WITH_YOUR_SSID&quot;;\nconst char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;\n\nvoid WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){\n  Serial.println(&quot;Connected to AP successfully!&quot;);\n}\n\nvoid WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){\n  Serial.println(&quot;WiFi connected&quot;);\n  Serial.println(&quot;IP address: &quot;);\n  Serial.println(WiFi.localIP());\n}\n\nvoid WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){\n  Serial.println(&quot;Disconnected from WiFi access point&quot;);\n  Serial.print(&quot;WiFi lost connection. Reason: &quot;);\n  Serial.println(info.wifi_sta_disconnected.reason);\n  Serial.println(&quot;Trying to Reconnect&quot;);\n  WiFi.begin(ssid, password);\n}\n\nvoid setup(){\n  Serial.begin(115200);\n\n  \/\/ delete old config\n  WiFi.disconnect(true);\n\n  delay(1000);\n\n  WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);\n  WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);\n  WiFi.onEvent(WiFiStationDisconnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);\n\n  \/* Remove WiFi event\n  Serial.print(&quot;WiFi Event ID: &quot;);\n  Serial.println(eventID);\n  WiFi.removeEvent(eventID);*\/\n\n  WiFi.begin(ssid, password);\n    \n  Serial.println();\n  Serial.println();\n  Serial.println(&quot;Wait for WiFi... &quot;);\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\/ESP32\/ESP32_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 three Wi-Fi events: when the ESP32 connects when it gets an IP address, and when it disconnects: <span class=\"rnthl rntliteral\">ARDUINO_EVENT_WIDI_STA_CONNECTED<\/span>, <span class=\"rnthl rntliteral\">ARDUINO_EVENT_WIFI_STA_GOT_IP<\/span>, and <span class=\"rnthl rntliteral\">ARDUINO_EVENT_WIFI_STA_DISCONNECTED<\/span>, respectively.<\/p>\n\n\n\n<p>When the ESP32 station connects to the access point (<span class=\"rnthl rntliteral\">ARDUINO_EVENT_WIFI_STA_CONNECTED<\/span> event), the <span class=\"rnthl rntliteral\">WiFiStationConnected()<\/span> function will be called:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code> WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);\n<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">WiFiStationConnected()<\/span> function simply prints that the ESP32 connected to an access point (for example, your router) successfully. 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 WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){\n  Serial.println(\"Connected to AP successfully!\");\n}<\/code><\/pre>\n\n\n\n<p>When the ESP32 gets its IP address, the <span class=\"rnthl rntliteral\">WiFiGotIP()<\/span> function runs. <\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);\n<\/code><\/pre>\n\n\n\n<p> That function simply prints the IP address on the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){\n  Serial.println(\"WiFi connected\");\n  Serial.println(\"IP address: \");\n  Serial.println(WiFi.localIP());\n}<\/code><\/pre>\n\n\n\n<p>When the ESP32 loses the connection with the access point (<span class=\"rnthl rntliteral\">ARDUINO_EVENT_WIFI_STA_DISCONNECTED<\/span>), the <span class=\"rnthl rntliteral\">WiFiStationDisconnected()<\/span> function is called.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code> WiFi.onEvent(WiFiStationDisconnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);\n<\/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 WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){\n  Serial.println(\"Disconnected from WiFi access point\");\n  Serial.print(\"WiFi lost connection. Reason: \");\n  Serial.println(info.disconnected.reason);\n  Serial.println(\"Trying to Reconnect\");\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 of how you can reconnect your ESP32 to a Wi-Fi network after the connection is lost.<\/p>\n\n\n\n<p>We recommend that you take a look at the following tutorial to better understand some of the most used ESP32 Wi-Fi functions:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-useful-wi-fi-functions-arduino\/\">ESP32 Useful Wi-Fi Library Functions (Arduino IDE)<\/a><\/li><\/ul>\n\n\n\n<p>One of the best applications of the ESP32 Wi-Fi capabilities is building web servers. If you want to use the ESP32 or ESP8266 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><\/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 how you can reconnect your ESP32 to a Wi-Fi network after losing the connection. This can be useful in the following scenarios: the ESP32 temporarily loses &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"[SOLVED] Reconnect ESP32 to Wi-Fi Network After Lost Connection\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/solved-reconnect-esp32-to-wifi\/#more-101925\" aria-label=\"Read more about [SOLVED] Reconnect ESP32 to Wi-Fi Network After Lost Connection\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":102002,"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":[281,276,277,299,264],"tags":[],"class_list":["post-101925","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp32-project","category-esp32","category-esp32-arduino-ide","category-0-esp32","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2021\/02\/ESP32-Reconnect-to-WiFi-After-Lost-Connection-Solved.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\/101925","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=101925"}],"version-history":[{"count":4,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/101925\/revisions"}],"predecessor-version":[{"id":120168,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/101925\/revisions\/120168"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/102002"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=101925"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=101925"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=101925"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}