My plan is to collect data from ESP32's CORE-1 and use ESP32's CORE-0 for all other tasks. However, I see that the variables are not updated properly when multiple cores are used. Here in this example, I see that the value of getAllData is updated only once.
const TickType_t xDelay = 1000 / portTICK_PERIOD_MS;
TaskHandle_t collectData;
bool volatile getAllData;
bool volatile dataReadyToSend;
void setup() {
Serial.begin(115200);
Serial.print("setup() is running on core ");
Serial.println(xPortGetCoreID());
xTaskCreatePinnedToCore(collectDataCode,"collectData",10000,NULL,1,&collectData,0);
delay(500);
}
void loop() {
if (Serial.available()) {
Serial.flush();
getAllData = true;
}
Serial.print("From loop: ");
Serial.println(getAllData);
if (dataReadyToSend) {
dataReadyToSend = false;
}
delay(1000);
}
void collectDataCode(void * params) {
while (1) {
Serial.print("From collectData: ");
Serial.println(getAllData);
if (getAllData) {
getAllData=0;
}
vTaskDelay( xDelay );
}
}
Output of the above code is given below. Where I typed xxx. It is observed that the variable getAllData got updated at this instance, but not changing later.
From collectData: 0
From loop: 0
From collectData: 0
From loop: 0
From collectData: 0
From loop: 0
From collectData: 0
From loop: 0
From collectData: 0
xxx
From loop: 1
From collectData: 1
From loop: 1
From collectData: 1
From loop: 1
From collectData: 1
From loop: 1
From collectData: 1
UPDATE
Upon suggestions, I used atomic with the following code. Still I see no success.
#ifdef __cplusplus
#include <atomic>
using namespace std;
#else
#include <stdatomic.h>
#endif
TaskHandle_t collectData;
atomic<bool> getAllData;
atomic<bool> dataReadyToSend;
#include "collectData.h"
void setup() {
Serial.begin(115200);
Serial.print("setup() is running on core ");
Serial.println(xPortGetCoreID());
xTaskCreatePinnedToCore(collectDataCode,"collectData",10000,NULL,1,&collectData,0);
delay(500);
}
void loop() {
if (Serial.available()) {
Serial.flush();
atomic_store (&getAllData, true);
}
Serial.print("From loop: ");
Serial.println(atomic_load(&getAllData));
if (dataReadyToSend) {
dataReadyToSend = false;
}
delay(1000);
}
void collectDataCode(void * params) {
while (1) {
Serial.print("From collectData: ");
Serial.println(atomic_load(&getAllData));
if (atomic_load(&getAllData)) {
atomic_store (&getAllData, false);
}
vTaskDelay( xDelay );
}
}
volatiledoesn't do anything for cross-thread synchronization. Usestd::atomic<bool>..atomic. I updated the question with theatomiccode.