Last active
November 17, 2018 20:28
-
-
Save Bolukan/9013404eb6a0ed1206eac52d7d6363f0 to your computer and use it in GitHub Desktop.
Best Practice Continuous WiFi Connection (WIP)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Arduino.h> | |
#if defined(ESP8266) | |
#include <ESP8266WiFi.h> | |
#elif defined(ESP32) | |
#include <WiFi.h> | |
#endif | |
// #include "secrets.h" | |
#ifndef SECRETS_H | |
#define SECRETS_H | |
const char WIFI_SSID[] = "WIFI_SSID_HERE"; | |
const char WIFI_PASSWORD[] = "WIFI_PASSWORD_HERE"; | |
#endif | |
/* | |
* Station connected | |
* @param WiFiEventStationModeConnected stationInfo struct of String ssid, uint8 bssid[6], uint8 channel | |
*/ | |
void onSTAConnected(WiFiEventStationModeConnected stationInfo) { | |
Serial.printf("Connected to %s\n", stationInfo.ssid.c_str()); | |
} | |
/* | |
* Got IP | |
* @param WiFiEventStationModeGotIP ipInfo struct of IPAddress ip, IPAddress mask, IPAddress gw | |
*/ | |
void onSTAGotIP(WiFiEventStationModeGotIP ipInfo) { | |
// Serial.printf(F("Connected: %s\n"), WiFi.status() == WL_CONNECTED ? "yes" : "no"); | |
// Serial.printf(F("Got IP: %s\n"), ipInfo.ip.toString().c_str()); | |
} | |
/* | |
* Station disconnected | |
* @param WiFiEventStationModeDisconnected disconnectedInfo struct of String ssid, uint8 bssid[6], WiFiDisconnectReason reason | |
* WiFiDisconnectReason, see https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiType.h | |
*/ | |
void onSTADisconnected(WiFiEventStationModeDisconnected disconnectInfo) { | |
// Serial.printf(F("Disconnected from SSID: %s\n"), disconnectInfo.ssid.c_str()); | |
// Serial.printf(F("Reason: %d\n"), disconnectInfo.reason); | |
// WiFi.reconnect(); | |
} | |
void connectToWiFi() { | |
// Serial.println(F("Connecting to WiFi ...")); | |
WiFi.persistent(false); | |
WiFi.mode(WIFI_STA); | |
WiFi.begin(WIFI_SSID, WIFI_PASSWORD); | |
} | |
void setup() { | |
// WiFi | |
static WiFiEventHandler e1, e2, e3; | |
// Other code. For example: Serial.begin(115200); | |
// WiFi | |
e1 = WiFi.onStationModeGotIP(onSTAGotIP); | |
e2 = WiFi.onStationModeConnected(onSTAConnected); | |
e3 = WiFi.onStationModeDisconnected(onSTADisconnected); | |
connectToWiFi(); | |
// Other code | |
} | |
void loop() { | |
// Use WiFi as client, server, etc | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment