In this tutorial, we will be looking ESP32 WiFi Events. WiFi Events are basically any states or conditions related to a WiFi connection ranging from being connected or disconnected to a WiFi, setting WiFi as Station Mode or SoftAP and etc. WiFi events are very useful as these events can happen at any point of time and we can trigger reactions accordingly. For instance during a Power CutOff, we can design the program to wait for connection to be up and running again until we move onto the next part of the program or code. It also makes our programming a little simpler.
Below is the code that we will be using in our tutorial.
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "WIFI NAME HERE";
char key[] = "WIFI PASSWORD HERE";
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.println("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.disconnected.reason);
Serial.println("Trying to Reconnect");
WiFi.begin(ssid, key);
}
void setup() {
Serial.begin(115200);
while (!Serial) {
}
//Events need to be declared first
//4 SYSTEM_EVENT_STA_CONNECTED < ESP32 station connected to AP
WiFi.onEvent(WiFiStationConnected, SYSTEM_EVENT_STA_CONNECTED);
//7 SYSTEM_EVENT_STA_GOT_IP < ESP32 station got IP from connected AP
WiFi.onEvent(WiFiGotIP, SYSTEM_EVENT_STA_GOT_IP);
//5 SYSTEM_EVENT_STA_DISCONNECTED < ESP32 station disconnected from AP
WiFi.onEvent(WiFiStationDisconnected, SYSTEM_EVENT_STA_DISCONNECTED);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, key);
delay(5000);
WiFi.disconnect();
delay(2000);
}
void loop() {
}
One important point to note is that we need to declare the events and its subsequent actions before the actual event happens. This will ensure the actual events are detected and the responses are triggered accordingly.
For more detailed instruction on this tutorial, feel free to check out my YouTube video below :
Comments