Skip to content

Instantly share code, notes, and snippets.

@DoganM95
Last active May 1, 2022 10:38
Show Gist options
  • Save DoganM95/995afbc8a053c59b1039f090ba8e2ef1 to your computer and use it in GitHub Desktop.
Save DoganM95/995afbc8a053c59b1039f090ba8e2ef1 to your computer and use it in GitHub Desktop.
Handles wifi connection in a separate thread in an esp32 to make wifi just work and enable focusing on the important stuff.
// Settings for Config.h
char* WIFI_SSID = "Your_WIFI_ssid";
char* WIFI_PW = "Your_WIFI_password";
// Main Code
int wifiConnectionTimeout = 10000;
ushort cycleDelayInMilliSeconds = 100;
const int wifiHandlerThreadStackSize = 10000;
unsigned long long wifiReconnectCounter = 0;
TaskHandle_t wifiConnectionHandlerThreadFunctionHandle;
void setup() { xTaskCreatePinnedToCore(wifiConnectionHandlerThreadFunction, "Wifi Connection Handling Thread", wifiHandlerThreadStackSize, NULL, 20, &wifiConnectionHandlerThreadFunctionHandle, 1); }
void wifiConnectionHandlerThreadFunction(void* params) {
uint time;
while (true) {
if (!WiFi.isConnected()) {
try {
Serial.printf("Connecting to Wifi: %s\n", WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PW); // initial begin as workaround to some espressif library bug
WiFi.disconnect();
WiFi.begin(WIFI_SSID, WIFI_PW);
WiFi.setHostname("Desklight (ESP32, Blynk)");
time = 0;
while (WiFi.status() != WL_CONNECTED) {
if (time >= wifiConnectionTimeout || WiFi.isConnected()) break;
delay(cycleDelayInMilliSeconds);
time += cycleDelayInMilliSeconds;
}
} catch (const std::exception e) {
Serial.printf("Error occured: %s\n", e.what());
}
if (WiFi.isConnected()) {
Serial.printf("Connected to Wifi: %s\n", WIFI_SSID);
wifiReconnectCounter = 0;
flashLights(2, 50, 50);
}
}
delay(1000);
Serial.printf("Wifi Connection Handler Thread current stack size: %d , current Time: %d\n", wifiHandlerThreadStackSize - uxTaskGetStackHighWaterMark(NULL), xTaskGetTickCount());
};
}
void WaitForWifi(uint cycleDelayInMilliSeconds) {
while (WiFi.status() != WL_CONNECTED) {
delay(cycleDelayInMilliSeconds);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment