10 years ago.

Missing volatile keyword?

The variables that can be modified via the pin change InterruptIn calls should really have a volatile keyword on them to preventing reading during a mid-update.

Question relating to:

Code to read a PPM/PWM pulse, interrupt driven. Most useful for RC receivers. Code is non-blocking, and a poll of the stall timer can detect if a signal has been … interrupt, PPM, pwm, RC, Receiver

I'm pretty volatile doesn't ensure atomic access, it just prevents the compiler from optimizing those variables out because it assumes nothing else will modify them. That's why you usually see it used with memory mapped I/O; the compiler doesn't know the machine will modify that memory location, and only sees that the code itself doesn't.

posted by Neil Thiessen 16 May 2014

@Neal, yes you're absolutely correct. Volatile does not ensure atomic access which I incorrectly alluded to.

posted by Jason Stapels 17 May 2014

Volatile declaration would solve only a part of the problem. Not only is it used to make sure the register is read instead of using an optimised cache, it can thus help when ISRs can modify globally defined variables. In the case of this library here, perhaps a mutex may help regarding atomic access? My understanding of a volatile variable is as explained, that it prevents compiler optimisation, hence why I think it is only a part of the solution. If we were to analyse this code, I dont think such guards are necessary? pulsewidth and period are only modified by one ISR each anyway! Instead I may just move those two variables to the protected space to prevent some nasty business. Thoughts anyone? Thank you everyone so far for your insight :)

posted by Ian Hua 17 May 2014

1 Answer

10 years ago.

Hi Jason!

Yes you are absolutely right. I will update this as soon as I get proper access to a computer.

Regards,

Ian

  • Edit: I've updated the library; pulsewidth and period are now volatile. Thanks Jason.

Accepted Answer