- Sat Oct 28, 2017 8:46 pm
#71332
On the subject of hwCount : I'm not going to say I have a definitive answer, but from my own experience, hwCount access from ISR and non-ISR should be fine in your case (it may not necessarily be 'best practice' but I have no real opinion on that for this reply).
The reason *I think* it's OK, is because your data type (of hwCount) happens to be a natural processor word (I.e. An int) AND there is only one writer - the read or write will be atomic as it will be a single uninterruptible load or store. If the data type were something like a 64-bit integer (long long), or an array/struct etc etc, then a possibility exists for partial loads/stores to be intermixed between what are in essence two threads. The assembler output should confirm this. I would not expect any kind of exception to occur even if the data got corrupted, because in your case it's just a plain old number, not an address calculation etc - you would just see an odd looking value when you printed it.
In addition lastHwCount does not have to be volatile, since it is only used by the non-ISR code (unless I missed it being used elsewhere). But otherwise, yes volatile is a bit of a red-herring as far as the exception is concerned.
Care should also be taken when using "non-int sized architectures" (like an Arduino Uno which has a 8-bits as its natural machine word) as using an int in this case would be in error, and you must use an 8-bit data type (char, or unsigned char) for hwCount. I am fairly certain of what I say here, as I have done a lot of testing with high resolution interrupts writing to shared queues with code common to Uno and esp8266, and I have seen the effects and ensured my code is compliant with what I just wrote above.