Skip to content

Instantly share code, notes, and snippets.

@DoganM95
Last active February 6, 2022 14:33
Show Gist options
  • Save DoganM95/a42e00a51e02846784292f0c98de0db3 to your computer and use it in GitHub Desktop.
Save DoganM95/a42e00a51e02846784292f0c98de0db3 to your computer and use it in GitHub Desktop.
ESP32 thread snippets
// Settings for Config.h
const char* BLYNK_AUTH = "AuthTokenGoesHere"; // Get the token in the Blynk app on your phone (project settings)
const bool BLYNK_USE_LOCAL_SERVER = false;
// Following settings are obsolete, if BLYNK_USE_LOCAL_SERVER is set to false
const char* BLYNK_SERVER = "yourBlynkServer.ddns.net";
const unsigned short int BLYNK_PORT = 8080;
// Code in sketch
const int BlynkHandlerThreadStackSize = 10000;
ushort cycleDelayInMilliSeconds = 100;
int blynkConnectionTimeout = 10000;
int blynkConnectionStabilizerTimeout = 5000;
const int blynkHandlerThreadStackSize = 10000;
TaskHandle_t blynkConnectionHandlerThreadFunctionHandle;
void setup() {
xTaskCreatePinnedToCore(blynkConnectionHandlerThreadFunction, "Blynk Connection Handling Thread", BlynkHandlerThreadStackSize, NULL, 20, &blynkConnectionHandlerThreadFunctionHandle, 1);
}
void loop() { Blynk.run(); }
void blynkConnectionHandlerThreadFunction(void* params) {
uint time;
while (true) {
if (!Blynk.connected()) {
Serial.printf("Connecting to Blynk: %s\n", BLYNK_USE_LOCAL_SERVER == true ? BLYNK_SERVER : "Blynk Cloud Server");
if (BLYNK_USE_LOCAL_SERVER)
Blynk.config(BLYNK_AUTH, BLYNK_SERVER, BLYNK_PORT);
else
Blynk.config(BLYNK_AUTH);
Blynk.connect(); // Connects using the chosen Blynk.config
uint time = 0;
while (!Blynk.connected()) {
if (time >= blynkConnectionTimeout || Blynk.connected()) break;
delay(cycleDelayInMilliSeconds);
time += cycleDelayInMilliSeconds;
}
if (Blynk.connected()) {
Serial.printf("Connected to Blynk: %s\n", BLYNK_USE_LOCAL_SERVER ? BLYNK_SERVER : "Blynk Cloud Server");
delay(blynkConnectionStabilizerTimeout);
}
}
delay(1000);
Serial.printf("Blynk Connection Handler Thread current stack size: %d , current Time: %d\n", blynkHandlerThreadStackSize - uxTaskGetStackHighWaterMark(NULL), xTaskGetTickCount());
}
}
void WaitForBlynk(int cycleDelayInMilliSeconds) {
while (!Blynk.connected()) {
delay(cycleDelayInMilliSeconds);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment