From ab1b90490c2fe5b2ae444a490ff2f43c83e6eb87 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 26 Apr 2020 02:27:38 -0700 Subject: [PATCH] opt-in ownership of PWM peripheral --- cores/nRF5/HardwarePWM.cpp | 19 +++++++++++++++++++ cores/nRF5/HardwarePWM.h | 13 +++++++++++++ 2 files changed, 32 insertions(+) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 9caaa860..9169d9c4 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -53,6 +53,25 @@ HardwarePWM* HwPWMx[] = #endif }; +// returns true ONLY when (1) no PWM channel has a pin, and (2) the owner token is nullptr +bool HardwarePWM::takeOwnership(uintptr_t token) +{ + if (this->_owner_token != 0) return false; // doesn't matter if it's actually a match ... it's not legal to take ownership twice + if (this->usedChannelCount() != 0) return false; // at least one channel is already in use + // use gcc built-in intrinsic to ensure atomicity + // See https://gcc.gnu.org/onlinedocs/gcc/_005f_005fsync-Builtins.html + return __sync_bool_compare_and_swap(&(this->_owner_token), 0, token); +} +// returns true ONLY when (1) no PWM channel has a pin attached, and (2) the owner token matches +bool HardwarePWM::releaseOwnership(uintptr_t token) +{ + if (!this->isOwner(token) ) return false; // don't even look at peripheral + if ( this->usedChannelCount() != 0) return false; // fail if any channels still have pins + // use gcc built-in intrinsic to ensure atomicity + // See https://gcc.gnu.org/onlinedocs/gcc/_005f_005fsync-Builtins.html + return __sync_bool_compare_and_swap(&(this->_owner_token), token, 0); +} + HardwarePWM::HardwarePWM(NRF_PWM_Type* pwm) { _pwm = pwm; diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index eaccff1f..5bfe6977 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -50,6 +50,7 @@ class HardwarePWM private: enum { MAX_CHANNELS = 4 }; // Max channel per group NRF_PWM_Type* _pwm; + uintptr_t _owner_token = 0; uint16_t _seq0[MAX_CHANNELS]; @@ -67,6 +68,18 @@ class HardwarePWM void setClockDiv(uint8_t div); // value is PWM_PRESCALER_PRESCALER_DIV_x, DIV1 is 16Mhz + // Cooperative ownership sharing + + // returns true ONLY when (1) no PWM channel has a pin, and (2) the owner token is nullptr + bool takeOwnership(uintptr_t token); + // returns true ONLY when (1) no PWM channel has a pin attached, and (2) the owner token matches + bool releaseOwnership(uintptr_t token); + // allows caller to verify that they own the peripheral + __INLINE bool isOwner(uintptr_t token) __attribute__((__always_inline__)) + { + return this->_owner_token == token; + } + bool addPin (uint8_t pin); bool removePin (uint8_t pin);