Thanks @rickkas7 . I followed the example you provided and implemented changes in my other project code. I remember now seeing this topic (atomically increment a variable in the ISR) in a thread with @chipmc but I did not utilize the concept until today:
https://community.particle.io/t/volatile-structures-and-eeprom/56865/5
I thought I would correct or "make better" the pseudocode I wrote earlier:
// Atomic variables - values are set and get atomically for use with ISR
std::atomic<uint32_t> pulseCount;
void isrTriggered() {
// This increments the value atomically. Even if the ISR triggers
// while we're resetting the value from loop, the count will
// not be lost.
pulseCount.fetch_add(1, std::memory_order_relaxed);
}
void setup() {
...
pulseCount.store(0, std::memory_order_relaxed);
pinMode(D3, INPUT);
attachInterrupt(D3, isrTriggered, FALLING);
...
}
void loop() {
static unsigned long lastCheck = 0;
if (millis() - lastCheck >= 1000) {
lastCheck = millis();
// Take the value from and clear it to 0 atomically. Even if
// the ISR triggers at this exact moment, "pulseCount" will either
// be updated before reading (.fetch_and), or after setting to 0, but never
// in the middle.
uint32_t tempPulseCount = pulseCount.fetch_and(0, std::memory_order_relaxed);
// process pulse count here
...
}
// all the rest here
...
}