/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/solved-reconnect-esp32-to-wifi/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
#include <WiFi.h>
#define pshBtn 5 // set push button pin
const char* ssid = "Wokwi-GUEST";
const char* password = "";
volatile bool pshBtnFlag = false;
void ICACHE_RAM_ATTR pshISR();
void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){
Serial.println("Connected to AP successfully!");
}
void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){
Serial.println("Disconnected from WiFi access point");
Serial.print("WiFi lost connection. Reason: ");
Serial.println(info.wifi_sta_disconnected.reason);
Serial.println("Trying to Reconnect");
WiFi.disconnect(false);
delay(3000);
WiFi.begin(ssid, password);
delay(3000);
WiFi.reconnect();
}
void setup(){
Serial.begin(115200);
WiFi.disconnect(true); // delete old config
delay(1000);
WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);
WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
WiFi.onEvent(WiFiStationDisconnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);
/* Remove WiFi event
Serial.print("WiFi Event ID: ");
Serial.println(eventID);
WiFi.removeEvent(eventID);*/
WiFi.begin(ssid, password);
Serial.println();
Serial.println();
Serial.println("Wait for WiFi... ");
pinMode(pshBtn, INPUT_PULLUP); // Initialize hardware GPIOs
attachInterrupt( // attach ISR
digitalPinToInterrupt(pshBtn), // to pshBtn pin
pshISR, // and pshBtnISR function
RISING);
}
void loop(){
if(pshBtnFlag == true) {
Serial.println("Disconnecting . . .");
WiFi.disconnect(true);
pshBtnFlag = false;
}
delay(1000);
}
/* -------------------- ISR Attached Function ------------------- */
void ICACHE_RAM_ATTR pshISR() { // PshISR attached int
static unsigned long lastDebounceTime = 0; // initalize debounce vars
const unsigned long debounceDelay = 200; // set debounce interval
if ((millis() - lastDebounceTime) > debounceDelay) { // debounce algorithm
pshBtnFlag = true; // set notify flag
}
lastDebounceTime = millis(); // set debounce millis
}
Loading
esp32-c3-devkitm-1
esp32-c3-devkitm-1