From 6f2adf4f62472e733e57b94a681fd1d728e54e12 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 01:22:35 +0700 Subject: [PATCH] fix possible race condition --- cores/nRF5/HardwarePWM.cpp | 14 ++++++++++---- libraries/Servo/src/nrf52/Servo.cpp | 14 +++++++++++--- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index adcfcaf3..b6e742ac 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -289,10 +289,13 @@ bool HardwarePWM::takeOwnership(uintptr_t token) // This function must not be called within ISR taskENTER_CRITICAL(); - _owner_token = token; + if ( this->_owner_token == 0 ) + { + _owner_token = token; + } taskEXIT_CRITICAL(); - return true; + return _owner_token == token; } // returns true ONLY when (1) no PWM channel has a pin attached, and (2) the owner token matches @@ -320,8 +323,11 @@ bool HardwarePWM::releaseOwnership(uintptr_t token) // This function must not be called within ISR taskENTER_CRITICAL(); - _owner_token = 0; + if ( this->_owner_token == token ) + { + _owner_token = 0; + } taskEXIT_CRITICAL(); - return true; + return _owner_token == 0; } diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp index 374baead..506a9519 100644 --- a/libraries/Servo/src/nrf52/Servo.cpp +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -48,11 +48,19 @@ uint8_t Servo::attach(int pin, int min, int max) } bool succeeded = false; - if (min < MIN_PULSE_WIDTH) min = MIN_PULSE_WIDTH; - if (max > MAX_PULSE_WIDTH) max = MAX_PULSE_WIDTH; + if (min < MIN_PULSE_WIDTH) + { + min = MIN_PULSE_WIDTH; + } + + if (max > MAX_PULSE_WIDTH) + { + max = MAX_PULSE_WIDTH; + } //fix min if conversion to pulse cycle value is too low - if ( (min/DUTY_CYCLE_RESOLUTION) * DUTY_CYCLE_RESOLUTION < min) { + if ( (min / DUTY_CYCLE_RESOLUTION) * DUTY_CYCLE_RESOLUTION < min ) + { min += DUTY_CYCLE_RESOLUTION; }