From 947d8bb6f7f8f5dbf25d8c4bfc2b1e6997c2e3da Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 25 Aug 2020 10:06:43 +0700 Subject: [PATCH 01/14] clean up pwn and analog replace built-in atomic with freeRTOS critical functions --- cores/nRF5/HardwarePWM.cpp | 141 +++++++++++++++++------------------ cores/nRF5/HardwarePWM.h | 6 +- cores/nRF5/wiring_analog.cpp | 67 +++++++---------- 3 files changed, 99 insertions(+), 115 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index f9927727..a6bf99bd 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -75,10 +75,8 @@ void HardwarePWM::DebugOutput(Stream& logger) logger.printf(" || %d:", i); if (can_stringify_token(token)) { uint8_t * t = (uint8_t*)(&token); - static_assert(sizeof(uintptr_t) == 4); logger.printf(" \"%c%c%c%c\"", t[0], t[1], t[2], t[3] ); } else { - static_assert(sizeof(uintptr_t) == 4); logger.printf(" %08x", token); } for (size_t j = 0; j < MAX_CHANNELS; j++) { @@ -96,76 +94,6 @@ void HardwarePWM::DebugOutput(Stream& logger) void HardwarePWM::DebugOutput(Stream& logger) {} #endif // CFG_DEBUG -// returns true ONLY when (1) no PWM channel has a pin, and (2) the owner token is nullptr -bool HardwarePWM::takeOwnership(uintptr_t token) -{ - bool notInIsr = !isInISR(); - if (token == 0) { - if (notInIsr) { - LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in takeOwnership)"); - } - return false; // cannot take ownership with nullptr - } - if (token == this->_owner_token) { - if (notInIsr) { - LOG_LV1("HwPWM", "failing to acquire ownership because already owned by requesting token (cannot take ownership twice)"); - } - } - if (this->_owner_token != 0) { - return false; - } - if (this->usedChannelCount() != 0) { - return false; - } - if (this->enabled()) { - return false; - } - // TODO: warn, but do not fail, if taking ownership with IRQs already enabled - // NVIC_GetActive - - // Use C++11 atomic CAS operation - uintptr_t newValue = 0U; - return this->_owner_token.compare_exchange_strong(newValue, 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) -{ - bool notInIsr = !isInISR(); - if (token == 0) { - if (notInIsr) { - LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in releaseOwnership)"); - } - return false; - } - if (!this->isOwner(token)) { - if (notInIsr) { - LOG_LV1("HwPWM", "attempt to release ownership when not the current owner"); - } - return false; - } - if (this->usedChannelCount() != 0) { - if (notInIsr) { - LOG_LV1("HwPWM", "attempt to release ownership when at least on channel is still connected"); - } - return false; - } - if (this->enabled()) { - if (notInIsr) { - LOG_LV1("HwPWM", "attempt to release ownership when PWM peripheral is still enabled"); - } - return false; // if it's enabled, do not allow ownership to be released, even with no pins in use - } - // TODO: warn, but do not fail, if releasing ownership with IRQs enabled - // NVIC_GetActive - - // Use C++11 atomic CAS operation - bool result = this->_owner_token.compare_exchange_strong(token, 0U); - if (!result) { - LOG_LV1("HwPWM", "race condition resulted in failure to acquire ownership"); - } - return result; -} - HardwarePWM::HardwarePWM(NRF_PWM_Type* pwm) : _pwm(pwm) { @@ -350,3 +278,72 @@ uint8_t HardwarePWM::freeChannelCount(void) const return MAX_CHANNELS - usedChannelCount(); } +// 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 (token == 0) { + LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in takeOwnership)"); + return false; + } + + if (token == this->_owner_token) { + LOG_LV1("HwPWM", "failing to acquire ownership because already owned by requesting token (cannot take ownership twice)"); + return false; + } + + if (this->_owner_token != 0) return false; + if (this->usedChannelCount() != 0) return false; + if (this->enabled()) return false; + + if (isInISR()) + { + UBaseType_t intr_status = taskENTER_CRITICAL_FROM_ISR(); + _owner_token = token; + taskEXIT_CRITICAL_FROM_ISR(intr_status); + }else + { + taskENTER_CRITICAL(); + _owner_token = token; + taskEXIT_CRITICAL(); + } + + return true; +} + +// 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 (token == 0) { + LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in releaseOwnership)"); + return false; + } + + if (!this->isOwner(token)) { + LOG_LV1("HwPWM", "attempt to release ownership when not the current owner"); + return false; + } + + if (this->usedChannelCount() != 0) { + LOG_LV1("HwPWM", "attempt to release ownership when at least on channel is still connected"); + return false; + } + + if (this->enabled()) { + LOG_LV1("HwPWM", "attempt to release ownership when PWM peripheral is still enabled"); + return false; // if it's enabled, do not allow ownership to be released, even with no pins in use + } + + if (isInISR()) + { + UBaseType_t intr_status = taskENTER_CRITICAL_FROM_ISR(); + _owner_token = 0; + taskEXIT_CRITICAL_FROM_ISR(intr_status); + }else + { + taskENTER_CRITICAL(); + _owner_token = 0; + taskEXIT_CRITICAL(); + } + + return true; +} diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index 024a8c84..9fd90b11 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -38,7 +38,6 @@ #include "common_inc.h" #include "nrf.h" -#include #ifdef NRF52840_XXAA #define HWPWM_MODULE_NUM 4 @@ -51,7 +50,7 @@ class HardwarePWM private: enum { MAX_CHANNELS = 4 }; // Max channel per group NRF_PWM_Type * const _pwm; - std::atomic_uintptr_t _owner_token; + uintptr_t _owner_token; uint16_t _seq0[MAX_CHANNELS]; @@ -73,11 +72,12 @@ class HardwarePWM // 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) const + bool isOwner(uintptr_t token) const { return this->_owner_token == token; } diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 7c1ac04f..750b3627 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -59,8 +59,10 @@ void analogWriteResolution( uint8_t res ) _analogResolution = res; for (int i = 0; iisOwner(_analogToken)) continue; - HwPWMx[i]->setResolution(res); + if (HwPWMx[i]->isOwner(_analogToken)) + { + HwPWMx[i]->setResolution(res); + } } } @@ -73,39 +75,30 @@ void analogWriteResolution( uint8_t res ) */ void analogWrite( uint32_t pin, uint32_t value ) { - /* If the pin is already in use for analogWrite, this should be fast - If the pin is not already in use, then it's OK to take slightly more time to setup - */ - // first, handle the case where the pin is already in use by analogWrite() for(int i=0; iisOwner(_analogToken)) { - continue; // skip if not owner of this PWM instance + if (HwPWMx[i]->isOwner(_analogToken)) + { + int const ch = HwPWMx[i]->pin2channel(pin); + if (ch >= 0) + { + HwPWMx[i]->writeChannel(ch, value); + return; + } } - - int const ch = HwPWMx[i]->pin2channel(pin); - if (ch < 0) { - continue; // pin not in use by this PWM instance - } - HwPWMx[i]->writeChannel(ch, value); - return; } // Next, handle the case where can add the pin to a PWM instance already owned by analogWrite() for(int i=0; iisOwner(_analogToken)) { - continue; + if ( HwPWMx[i]->isOwner(_analogToken) && HwPWMx[i]->addPin(pin) ) + { + // successfully added the pin, so write the value also + LOG_LV2("Analog", "Added pin %" PRIu32 " to already-owned PWM %d", pin, i); + HwPWMx[i]->writePin(pin, value); + return; } - if (!HwPWMx[i]->addPin(pin)) { - continue; - } - - // successfully added the pin, so write the value also - LOG_LV2("ANA", "Added pin %" PRIu32 " to already-owned PWM %d", pin, i); - HwPWMx[i]->writePin(pin, value); - return; } // Attempt to acquire a new HwPWMx instance ... but only where @@ -113,25 +106,19 @@ void analogWrite( uint32_t pin, uint32_t value ) // 2. it currently has no pins in use. for(int i=0; itakeOwnership(_analogToken)) { - continue; + if (HwPWMx[i]->takeOwnership(_analogToken)) + { + // apply the cached analog resolution to newly owned instances + HwPWMx[i]->setResolution(_analogResolution); + HwPWMx[i]->addPin(pin); + HwPWMx[i]->writePin(pin, value); + LOG_LV2("Analog", "took ownership of, and added pin %" PRIu32 " to, PWM %d", pin, i); + return; } - - // apply the cached analog resolution to newly owned instances - HwPWMx[i]->setResolution(_analogResolution); - HwPWMx[i]->addPin(pin); - HwPWMx[i]->writePin(pin, value); - LOG_LV2("ANA", "took ownership of, and added pin %" PRIu32 " to, PWM %d", pin, i); - return; } - // failed to allocate a HwPWM instance. - // output appropriate debug message. - LOG_LV1("ANA", "Unable to find a free PWM peripheral"); - // TODO: Add additional diagnostics to function at higher log levels + LOG_LV1("Analog", "Unable to find a free PWM peripheral"); return; } } // end extern "C" - - From 019b1c248e18b494360b90029952986cde0e5389 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 25 Aug 2020 11:49:45 +0700 Subject: [PATCH 02/14] servo clean up --- cores/nRF5/HardwarePWM.cpp | 2 +- libraries/Servo/src/Servo.h | 4 +-- libraries/Servo/src/nrf52/Servo.cpp | 48 ++++++++++++++++------------- 3 files changed, 30 insertions(+), 24 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index a6bf99bd..f3defad4 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -224,7 +224,7 @@ void HardwarePWM::stop(void) _pwm->ENABLE = 0; } -bool HardwarePWM::writeChannel(uint8_t ch, uint16_t value, bool inverted ) +bool HardwarePWM::writeChannel(uint8_t ch, uint16_t value, bool inverted) { VERIFY( ch < MAX_CHANNELS ); diff --git a/libraries/Servo/src/Servo.h b/libraries/Servo/src/Servo.h index 28df7462..af145caa 100644 --- a/libraries/Servo/src/Servo.h +++ b/libraries/Servo/src/Servo.h @@ -111,8 +111,8 @@ public: bool attached(); // return true if this servo is attached, otherwise false private: uint8_t servoIndex; // index into the channel data for this servo - int16_t min; // minimum pulse in µs - int16_t max; // maximum pulse in µs + int16_t min; // minimum pulse in µs + int16_t max; // maximum pulse in µs HardwarePWM* pwm; }; diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp index 02995550..374baead 100644 --- a/libraries/Servo/src/nrf52/Servo.cpp +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -47,41 +47,37 @@ uint8_t Servo::attach(int pin, int min, int max) return INVALID_SERVO; } bool succeeded = false; - pinMode(pin, OUTPUT); // set servo pin to output - servos[this->servoIndex].Pin.nbr = pin; - 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) { min += DUTY_CYCLE_RESOLUTION; } - this->min = min; - this->max = max; - - servos[this->servoIndex].Pin.isActive = true; + this->min = min; + this->max = max; // Adafruit, add pin to 1 of available Hw PWM // first, use existing HWPWM modules (already owned by Servo) - for(int i=0; iisOwner(_servoToken) && - HwPWMx[i]->addPin(pin)) { + for ( int i = 0; i < HWPWM_MODULE_NUM; i++ ) + { + if ( HwPWMx[i]->isOwner(_servoToken) && HwPWMx[i]->addPin(pin) ) + { this->pwm = HwPWMx[i]; succeeded = true; break; } } + // if could not add to existing owned PWM modules, try to add to a new PWM module - if (!succeeded) { - for(int i=0; itakeOwnership(_servoToken) && - HwPWMx[i]->addPin(pin)) { + if ( !succeeded ) + { + for ( int i = 0; i < HWPWM_MODULE_NUM; i++ ) + { + if ( HwPWMx[i]->takeOwnership(_servoToken) && HwPWMx[i]->addPin(pin) ) + { this->pwm = HwPWMx[i]; succeeded = true; break; @@ -89,11 +85,20 @@ uint8_t Servo::attach(int pin, int min, int max) } } - if (succeeded) { // do not use this->pwm unless success above! + if ( succeeded ) + { + pinMode(pin, OUTPUT); + servos[this->servoIndex].Pin.nbr = pin; + servos[this->servoIndex].Pin.isActive = true; + this->pwm->setMaxValue(MAXVALUE); this->pwm->setClockDiv(CLOCKDIV); + + return this->servoIndex; + }else + { + return INVALID_SERVO; } - return succeeded ? this->servoIndex : INVALID_SERVO; // return INVALID_SERVO on failure (zero is a valid servo index) } void Servo::detach() @@ -104,6 +109,7 @@ void Servo::detach() uint8_t const pin = servos[this->servoIndex].Pin.nbr; servos[this->servoIndex].Pin.isActive = false; + // remove pin from HW PWM HardwarePWM * pwm = this->pwm; this->pwm = nullptr; From cca5adaa518710927b8a07a517e797b8bba284bf Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 25 Aug 2020 16:46:26 +0700 Subject: [PATCH 03/14] start to clean up tone --- .travis.yml.bck | 68 -------------------------------------- cores/nRF5/HardwarePWM.cpp | 16 +++++---- cores/nRF5/Tone.cpp | 24 ++++++-------- 3 files changed, 20 insertions(+), 88 deletions(-) delete mode 100644 .travis.yml.bck diff --git a/.travis.yml.bck b/.travis.yml.bck deleted file mode 100644 index 91a585eb..00000000 --- a/.travis.yml.bck +++ /dev/null @@ -1,68 +0,0 @@ -sudo: required -language: c -dist: xenial -git: - depth: false - quiet: true - -env: - global: - - BSP_PATH="$HOME/.arduino15/packages/adafruit/hardware/nrf52" - jobs: - # empty env required, else allow_failures will SILENTY IGNORE matching against env... - - - -jobs: - fast_finish: true - include: - - name: "Feather nRF52840" - env: VARIANT="feather52840" - - name: "Feather nRF52840 (All warnings)" - env: ALL_WARNINGS="true" VARIANT="feather52840" - - name: "Circuit Playground nRF52840" - env: VARIANT="cplaynrf52840" - - name: "Circuit Playground nRF52840 (All warnings)" - env: ALL_WARNINGS="true" VARIANT="cplaynrf52840" - - name: "Feather nRF52832" - env: VARIANT="feather52832" - - name: "Feather nRF52832 (All warnings)" - env: ALL_WARNINGS="true" VARIANT="feather52832" - - name: "ItsyBitsy nRF52840 Express" - env: VARIANT="itsybitsy52840" - - name: "Clue nRF52840" - env: VARIANT="cluenrf52840" - allow_failures: - - env: ALL_WARNINGS="true" VARIANT="feather52840" - - env: ALL_WARNINGS="true" VARIANT="cplaynrf52840" - - env: ALL_WARNINGS="true" VARIANT="feather52832" - -addons: - apt: - packages: - - python3 - - python3-pip - - python3-setuptools - snaps: - - name: ubuntu-make - confinement: classic - -install: - # Filter only mDNS / Bonjour traffic - - sudo iptables --insert INPUT --jump DROP --protocol udp --dport 5353 -m comment --comment "silently drop all 5353/udp input" - - sudo iptables --insert INPUT --jump DROP --destination 224.0.0.251 -m comment --comment "silently drop all mDNS ipv4 broadcast" - # Install the nRF52 support files for arduino - - pip3 install --user adafruit-nrfutil - - umake electronics arduino $HOME/arduino_ide - - export PATH=$HOME/arduino_ide:$PATH - - arduino --pref "boardsmanager.additional.urls=https://adafruit.github.io/arduino-board-index/package_adafruit_index.json" --save-prefs - # Install BSP for tools, then remove and create symlink the git code - - arduino --install-boards adafruit:nrf52 - - BSP_VERSION=`eval ls $BSP_PATH` - - rm -r $BSP_PATH/* - - ln -s $TRAVIS_BUILD_DIR $BSP_PATH/$BSP_VERSION - - arduino --install-library "Adafruit NeoPixel","Adafruit NeoMatrix","Adafruit GFX Library","Adafruit SSD1306","MIDI Library","Adafruit ILI9341","Adafruit HX8357 Library","Adafruit Circuit Playground" - -before_script: - -script: - - python3 tools/build_all_travis.py diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index f3defad4..9b6cebe1 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -291,16 +291,17 @@ bool HardwarePWM::takeOwnership(uintptr_t token) return false; } - if (this->_owner_token != 0) return false; - if (this->usedChannelCount() != 0) return false; - if (this->enabled()) return false; + if ( this->_owner_token != 0 ) return false; + if ( this->usedChannelCount() != 0 ) return false; + if ( this->enabled() ) return false; - if (isInISR()) + if ( isInISR() ) { UBaseType_t intr_status = taskENTER_CRITICAL_FROM_ISR(); _owner_token = token; taskEXIT_CRITICAL_FROM_ISR(intr_status); - }else + } + else { taskENTER_CRITICAL(); _owner_token = token; @@ -333,12 +334,13 @@ bool HardwarePWM::releaseOwnership(uintptr_t token) return false; // if it's enabled, do not allow ownership to be released, even with no pins in use } - if (isInISR()) + if ( isInISR() ) { UBaseType_t intr_status = taskENTER_CRITICAL_FROM_ISR(); _owner_token = 0; taskEXIT_CRITICAL_FROM_ISR(intr_status); - }else + } + else { taskENTER_CRITICAL(); _owner_token = 0; diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 27a8a88a..462af999 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -48,22 +48,16 @@ static HardwarePWM * const _HwPWM = HwPWMx[2]; // Defined a struct, to simplify validation testing ... also provides context when debugging class TonePwmConfig { private: - const nrf_pwm_clk_t clock_frequency = NRF_PWM_CLK_125kHz; - const nrf_pwm_mode_t pwm_mode = NRF_PWM_MODE_UP; - const nrf_pwm_dec_step_t step_mode = NRF_PWM_STEP_AUTO; - const nrf_pwm_dec_load_t load_mode = NRF_PWM_LOAD_COMMON; const uintptr_t toneToken = 0x656e6f54; //< 'T' 'o' 'n' 'e' - private: uint64_t pulse_count; //< total number of PWM pulses uint32_t seq0_refresh; //< count of pulses for each SEQ0 iteration uint32_t seq1_refresh; //< count of pulses for each SEQ1 iteration uint16_t loop_count; //< how many times to restart SEQ0/SEQ1? uint16_t time_period; //< how many clock cycles allocated to each PWM pulse? uint16_t duty_with_polarity; //< SEQ[N].PTR will point here, length == 1 - uint8_t arduino_pin; //< the arduino pin for playback - uint8_t nrf_pin; //< the nrf pin for playback nrf_pwm_task_t task_to_start; //< Whether to start playback at SEQ0 or SEQ1 nrf_pwm_short_mask_t shorts; //< shortcuts to enable + public: bool ensurePwmPeripheralOwnership(void); bool initializeFromPulseCountAndTimePeriod(uint64_t pulse_count, uint16_t time_period); @@ -98,6 +92,7 @@ constexpr static uint16_t _calculate_time_period(uint32_t frequency) { // which fits in 16 bits. return 125000 / frequency; }; + constexpr static uint64_t _calculate_pulse_count(uint32_t frequency, uint32_t duration) { // range for frequency == [20..25000], // range for duration == [ 1..0xFFFF_FFFF] @@ -111,6 +106,7 @@ constexpr static uint64_t _calculate_pulse_count(uint32_t frequency, uint32_t du (duration / 1000ULL) * frequency : (((uint64_t)duration) * frequency / 1000ULL); }; + static int _bits_used(unsigned long x) { if (0 == x) return 0; unsigned int result = 0; @@ -119,6 +115,7 @@ static int _bits_used(unsigned long x) { } while (x >>= 1); return result; } + static int _bits_used(unsigned long long x) { if (0 == x) return 0; unsigned int result = 0; @@ -193,6 +190,7 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) } return; } + void noTone(uint8_t pin) { ( void )pin; // avoid unreferenced parameter compiler warning @@ -310,6 +308,7 @@ bool TonePwmConfig::initializeFromPulseCountAndTimePeriod(uint64_t pulse_count_x } return true; } + bool TonePwmConfig::applyConfiguration(uint32_t pin) { if (pin >= PINS_COUNT) { return false; @@ -319,11 +318,8 @@ bool TonePwmConfig::applyConfiguration(uint32_t pin) { } this->stopPlayback(false); - this->arduino_pin = pin; - this->nrf_pin = g_ADigitalPinMap[pin]; - uint32_t pins[NRF_PWM_CHANNEL_COUNT] = { - this->nrf_pin, + g_ADigitalPinMap[pin], NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED @@ -331,8 +327,8 @@ bool TonePwmConfig::applyConfiguration(uint32_t pin) { nrf_pwm_pins_set(_PWMInstance, pins); // must set pins before enabling nrf_pwm_enable(_PWMInstance); - nrf_pwm_configure(_PWMInstance, TonePwmConfig::clock_frequency, TonePwmConfig::pwm_mode, this->time_period); - nrf_pwm_decoder_set(_PWMInstance, TonePwmConfig::load_mode, TonePwmConfig::step_mode); + nrf_pwm_configure(_PWMInstance, NRF_PWM_CLK_125kHz, NRF_PWM_MODE_UP, this->time_period); + nrf_pwm_decoder_set(_PWMInstance, NRF_PWM_LOAD_COMMON, NRF_PWM_STEP_AUTO); nrf_pwm_shorts_set(_PWMInstance, this->shorts); nrf_pwm_int_set(_PWMInstance, 0); @@ -362,6 +358,7 @@ bool TonePwmConfig::applyConfiguration(uint32_t pin) { nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_LOOPSDONE); return true; } + bool TonePwmConfig::startPlayback(void) { if (!this->ensurePwmPeripheralOwnership()) { LOG_LV1("TON", "PWM peripheral not available for playback"); @@ -370,6 +367,7 @@ bool TonePwmConfig::startPlayback(void) { nrf_pwm_task_trigger(_PWMInstance, this->task_to_start); return true; } + bool TonePwmConfig::stopPlayback(bool releaseOwnership) { bool notInIsr = !isInISR(); From c3f8e3479067b3821bf16619867defc10e821bf7 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 25 Aug 2020 17:50:08 +0700 Subject: [PATCH 04/14] refactor hardware pwm --- cores/nRF5/HardwarePWM.cpp | 120 ++++++++++++++++------------------- cores/nRF5/HardwarePWM.h | 10 ++- cores/nRF5/wiring_analog.cpp | 2 +- 3 files changed, 65 insertions(+), 67 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 9b6cebe1..55c229ca 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -107,6 +107,38 @@ HardwarePWM::HardwarePWM(NRF_PWM_Type* pwm) : _pwm->PSEL.OUT[1] = 0xFFFFFFFFUL; } +void HardwarePWM::begin(void) +{ + // Initialize Registers + _pwm->MODE = PWM_MODE_UPDOWN_Up; + _pwm->COUNTERTOP = _max_value; // default is 255 (8 bit), can be configured before begin() + _pwm->PRESCALER = _clock_div; + _pwm->DECODER = PWM_DECODER_LOAD_Individual; + _pwm->LOOP = 0; + + _pwm->SEQ[0].PTR = (uint32_t) _seq0; + _pwm->SEQ[0].CNT = MAX_CHANNELS; // default mode is Individual --> count must be 4 + _pwm->SEQ[0].REFRESH = 0; + _pwm->SEQ[0].ENDDELAY = 0; + + _pwm->SEQ[1].PTR = 0; + _pwm->SEQ[1].CNT = 0; + _pwm->SEQ[1].REFRESH = 0; + _pwm->SEQ[1].ENDDELAY = 0; + + _pwm->ENABLE = 1; +} + +void HardwarePWM::stop(void) +{ + _pwm->ENABLE = 0; +} + +bool HardwarePWM::enabled (void) +{ + return _pwm->ENABLE; +} + void HardwarePWM::setResolution(uint8_t bitnum) { setMaxValue( bit(min8(bitnum, 15)) -1 ); @@ -124,6 +156,25 @@ void HardwarePWM::setClockDiv(uint8_t div) _pwm->PRESCALER = _clock_div; } +void HardwarePWM::_set_psel(int ch, uint32_t value) +{ + // Must disable before changing PSEL + if ( enabled() ) + { + _pwm->ENABLE = 0; + _pwm->PSEL.OUT[ch] = value; + _seq0[ch] = 0; + _pwm->ENABLE = 1; + + // re-start sequence + if ( usedChannelCount() ) _pwm->TASKS_SEQSTART[0] = 1; + }else + { + _pwm->PSEL.OUT[ch] = value; + _seq0[ch] = 0; + } +} + /** * Add pin to this group. * @param pin Pin to add @@ -150,17 +201,7 @@ bool HardwarePWM::addPin(uint8_t pin) pinMode(pin, OUTPUT); digitalWrite(pin, LOW); - // Must disable before changing PSEL - if ( enabled() ) - { - _pwm->ENABLE = 0; - _pwm->PSEL.OUT[ch] = g_ADigitalPinMap[pin]; - _pwm->ENABLE = 1; - _start(); - }else - { - _pwm->PSEL.OUT[ch] = g_ADigitalPinMap[pin]; - } + _set_psel(ch, g_ADigitalPinMap[pin]); return true; } @@ -170,70 +211,21 @@ bool HardwarePWM::removePin(uint8_t pin) int ch = pin2channel(pin); VERIFY( ch >= 0 ); - bool const en = enabled(); - - // Must disable before changing PSEL - if ( en ) _pwm->ENABLE = 0; - - _pwm->PSEL.OUT[ch] = 0xFFFFFFFFUL; - _seq0[ch] = 0; - - if ( en ) _pwm->ENABLE = 1; - + _set_psel(ch, 0xFFFFFFFFUL); return true; } -bool HardwarePWM::enabled (void) -{ - return _pwm->ENABLE; -} - -void HardwarePWM::begin(void) -{ - // Initialize Registers - _pwm->MODE = PWM_MODE_UPDOWN_Up; - _pwm->COUNTERTOP = _max_value; // default is 255 (8 bit), can be configured before begin() - _pwm->PRESCALER = _clock_div; - _pwm->DECODER = PWM_DECODER_LOAD_Individual; - _pwm->LOOP = 0; - - _pwm->SEQ[0].PTR = (uint32_t) _seq0; - _pwm->SEQ[0].CNT = MAX_CHANNELS; // default mode is Individual --> count must be 4 - _pwm->SEQ[0].REFRESH = 0; - _pwm->SEQ[0].ENDDELAY = 0; - - _pwm->SEQ[1].PTR = 0; - _pwm->SEQ[1].CNT = 0; - _pwm->SEQ[1].REFRESH = 0; - _pwm->SEQ[1].ENDDELAY = 0; - - _pwm->ENABLE = 1; -} - -void HardwarePWM::_start(void) -{ - // update sequence count (depending on mode) - // _pwm->SEQ[0].CNT = MAX_CHANNELS; - - // start sequence - _pwm->TASKS_SEQSTART[0] = 1; -} - -void HardwarePWM::stop(void) -{ - _pwm->ENABLE = 0; -} - bool HardwarePWM::writeChannel(uint8_t ch, uint16_t value, bool inverted) { VERIFY( ch < MAX_CHANNELS ); _seq0[ch] = value | (inverted ? 0 : bit(15)); - // Start PWM if not already + // Initialize PWM if not already if ( !enabled() ) begin(); - _start(); + // start sequence + _pwm->TASKS_SEQSTART[0] = 1; return true; } diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index 9fd90b11..188c6889 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -57,8 +57,6 @@ class HardwarePWM uint16_t _max_value; uint8_t _clock_div; - void _start(void); - public: HardwarePWM(NRF_PWM_Type* pwm); @@ -82,9 +80,13 @@ class HardwarePWM return this->_owner_token == token; } + // Add a pin to PWM module bool addPin (uint8_t pin); + + // Remove a pin from PWM module bool removePin (uint8_t pin); + // Get the mapped channel of a pin int pin2channel(uint8_t pin) const { pin = g_ADigitalPinMap[pin]; @@ -95,6 +97,7 @@ class HardwarePWM return (-1); } + // Check if pin is controlled by PWM bool checkPin(uint8_t pin) const { return pin2channel(pin) >= 0; @@ -117,6 +120,9 @@ class HardwarePWM uint8_t freeChannelCount(void) const; static void DebugOutput(Stream& logger); + + private: + void _set_psel(int ch, uint32_t value); }; extern HardwarePWM HwPWM0; diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 750b3627..93c78fbb 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -95,8 +95,8 @@ void analogWrite( uint32_t pin, uint32_t value ) if ( HwPWMx[i]->isOwner(_analogToken) && HwPWMx[i]->addPin(pin) ) { // successfully added the pin, so write the value also - LOG_LV2("Analog", "Added pin %" PRIu32 " to already-owned PWM %d", pin, i); HwPWMx[i]->writePin(pin, value); + LOG_LV2("Analog", "Added pin %" PRIu32 " to already-owned PWM %d", pin, i); return; } } From 1f2b65bd4569ab771d840b893cc1dfc884d958db Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 25 Aug 2020 18:00:54 +0700 Subject: [PATCH 05/14] disable PWM ownership within ISR() takeOwnership / releaseOwnership must be called in thread-context --- cores/nRF5/HardwarePWM.cpp | 32 ++++++++------------------------ 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 55c229ca..adcfcaf3 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -287,18 +287,10 @@ bool HardwarePWM::takeOwnership(uintptr_t token) if ( this->usedChannelCount() != 0 ) return false; if ( this->enabled() ) return false; - if ( isInISR() ) - { - UBaseType_t intr_status = taskENTER_CRITICAL_FROM_ISR(); - _owner_token = token; - taskEXIT_CRITICAL_FROM_ISR(intr_status); - } - else - { - taskENTER_CRITICAL(); - _owner_token = token; - taskEXIT_CRITICAL(); - } + // This function must not be called within ISR + taskENTER_CRITICAL(); + _owner_token = token; + taskEXIT_CRITICAL(); return true; } @@ -326,18 +318,10 @@ bool HardwarePWM::releaseOwnership(uintptr_t token) return false; // if it's enabled, do not allow ownership to be released, even with no pins in use } - if ( isInISR() ) - { - UBaseType_t intr_status = taskENTER_CRITICAL_FROM_ISR(); - _owner_token = 0; - taskEXIT_CRITICAL_FROM_ISR(intr_status); - } - else - { - taskENTER_CRITICAL(); - _owner_token = 0; - taskEXIT_CRITICAL(); - } + // This function must not be called within ISR + taskENTER_CRITICAL(); + _owner_token = 0; + taskEXIT_CRITICAL(); return true; } From ac9063395d65ecbade30f240a9b2e2535724bbd9 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 25 Aug 2020 18:09:31 +0700 Subject: [PATCH 06/14] more clean up --- cores/nRF5/Tone.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 462af999..df33e34f 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -370,13 +370,9 @@ bool TonePwmConfig::startPlayback(void) { bool TonePwmConfig::stopPlayback(bool releaseOwnership) { - bool notInIsr = !isInISR(); - if (!_HwPWM->isOwner(TonePwmConfig::toneToken)) { - if (notInIsr) { - LOG_LV2("TON", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); - } - return false; + LOG_LV2("TON", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); + return false; } // ensure stopped and then disable if (_is_pwm_enabled(_PWMInstance)) { @@ -388,5 +384,6 @@ bool TonePwmConfig::stopPlayback(bool releaseOwnership) { if (releaseOwnership) { _HwPWM->releaseOwnership(TonePwmConfig::toneToken); } + return true; } From 3aed8f784b73ad8c7b7f4588a10a787b93d10a74 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 25 Aug 2020 23:47:32 +0700 Subject: [PATCH 07/14] add tone happy birthday example this is mainly for testing functionality when refactoring tone() --- .../tone_happy_birthday.ino | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 libraries/Bluefruit52Lib/examples/Hardware/tone_happy_birthday/tone_happy_birthday.ino diff --git a/libraries/Bluefruit52Lib/examples/Hardware/tone_happy_birthday/tone_happy_birthday.ino b/libraries/Bluefruit52Lib/examples/Hardware/tone_happy_birthday/tone_happy_birthday.ino new file mode 100644 index 00000000..db4656e3 --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Hardware/tone_happy_birthday/tone_happy_birthday.ino @@ -0,0 +1,146 @@ +// Circuit Playground Birthday Candles +// +// All the NeoPixels will flicker like candles and the speaker will +// play the tune to Happy Birthday continuously. Blow on the board +// to slowly blow out all the candles and hear a victory song! +// Controls: +// - Slide switch: Move this to +/on to hear music or -/off to disable sound. +// - Left button: Hold this down and press reset to use a rainbow flicker color. +// - Right button: Hold this down and press reset to use a simple solid color (no flicker). +// - If neither left or right button are pressed at startup then a flame-like +// flickering animation will be used. +// After all the candles are blown out press reset to reset and start over! +// +// Author: Tony DiCola +// License: MIT (https://opensource.org/licenses/MIT) + +#include + +// PIN_BUZZER should be defined by the supported variant e.g CPlay Bluefruit or CLUE. +// Otherwise please define the pin you would like to use for tone output +#ifndef PIN_BUZZER +#define PIN_BUZZER 5 +#endif + + +// A few music note frequencies as defined in this tone example: +// https://www.arduino.cc/en/Tutorial/toneMelody +#define NOTE_C4 262 +#define NOTE_CS4 277 +#define NOTE_D4 294 +#define NOTE_DS4 311 +#define NOTE_E4 330 +#define NOTE_F4 349 +#define NOTE_FS4 370 +#define NOTE_G4 392 +#define NOTE_GS4 415 +#define NOTE_A4 440 +#define NOTE_AS4 466 +#define NOTE_B4 494 +#define NOTE_C5 523 +#define NOTE_CS5 554 +#define NOTE_D5 587 +#define NOTE_DS5 622 +#define NOTE_E5 659 +#define NOTE_F5 698 +#define NOTE_FS5 740 +#define NOTE_G5 784 +#define NOTE_GS5 831 +#define NOTE_A5 880 +#define NOTE_AS5 932 +#define NOTE_B5 988 + +// Define note durations. You only need to adjust the whole note +// time and other notes will be subdivided from it directly. +#define WHOLE 2200 // Length of time in milliseconds of a whole note (i.e. a full bar). +#define HALF WHOLE/2 +#define QUARTER HALF/2 +#define EIGHTH QUARTER/2 +#define EIGHTH_TRIPLE QUARTER/3 +#define SIXTEENTH EIGHTH/2 + +// Play a note of the specified frequency and for the specified duration. +// Hold is an optional bool that specifies if this note should be held a +// little longer, i.e. for eigth notes that are tied together. +// While waiting for a note to play the waitBreath delay function is used +// so breath detection and pixel animation continues to run. No tones +// will play if the slide switch is in the -/off position or all the +// candles have been blown out. +void playNote(int frequency, int duration, bool hold=false, bool measure=true) { + (void) measure; + + if (hold) { + // For a note that's held play it a little longer than the specified duration + // so it blends into the next tone (but there's still a small delay to + // hear the next note). + tone(PIN_BUZZER, frequency, duration + duration/32); + } + else { + // For a note that isn't held just play it for the specified duration. + tone(PIN_BUZZER, frequency, duration); + } + + delay(duration + duration/16); +} + +// Song to play when the candles are blown out. +void celebrateSong() { + // Play a little charge melody, from: + // https://en.wikipedia.org/wiki/Charge_(fanfare) + // Note the explicit boolean parameters in particular the measure=false + // at the end. This means the notes will play without any breath measurement + // logic. Without this false value playNote will try to keep waiting for candles + // to blow out during the celebration song! + playNote(NOTE_G4, EIGHTH_TRIPLE, true, false); + playNote(NOTE_C5, EIGHTH_TRIPLE, true, false); + playNote(NOTE_E5, EIGHTH_TRIPLE, false, false); + playNote(NOTE_G5, EIGHTH, true, false); + playNote(NOTE_E5, SIXTEENTH, false); + playNote(NOTE_G5, HALF, false); +} + +void setup() { + // Initialize serial output and Circuit Playground library. + Serial.begin(115200); + + pinMode(PIN_BUZZER, OUTPUT); + digitalWrite(PIN_BUZZER, LOW); +} + +void loop() { + // Play happy birthday tune, from: + // http://www.irish-folk-songs.com/happy-birthday-tin-whistle-sheet-music.html#.WXFJMtPytBw + // Inside each playNote call it will play a note and drive the NeoPixel animation + // and check for a breath against the sound sensor. Once all the candles are blown out + // the playNote calls will stop playing music. + playNote(NOTE_D4, EIGHTH, true); + playNote(NOTE_D4, EIGHTH); + playNote(NOTE_E4, QUARTER); // Bar 1 + playNote(NOTE_D4, QUARTER); + playNote(NOTE_G4, QUARTER); + playNote(NOTE_FS4, HALF); // Bar 2 + playNote(NOTE_D4, EIGHTH, true); + playNote(NOTE_D4, EIGHTH); + playNote(NOTE_E4, QUARTER); // Bar 3 + playNote(NOTE_D4, QUARTER); + playNote(NOTE_A4, QUARTER); + playNote(NOTE_G4, HALF); // Bar 4 + playNote(NOTE_D4, EIGHTH, true); + playNote(NOTE_D4, EIGHTH); + playNote(NOTE_D5, QUARTER); // Bar 5 + playNote(NOTE_B4, QUARTER); + playNote(NOTE_G4, QUARTER); + playNote(NOTE_FS4, QUARTER); // Bar 6 + playNote(NOTE_E4, QUARTER); + playNote(NOTE_C5, EIGHTH, true); + playNote(NOTE_C5, EIGHTH); + playNote(NOTE_B4, QUARTER); // Bar 7 + playNote(NOTE_G4, QUARTER); + playNote(NOTE_A4, QUARTER); + playNote(NOTE_G4, HALF); // Bar 8 + + celebrateSong(); + + // One second pause before repeating the loop and playing + delay(1000); +} From 0205da555abbc81593c50df00b8085e796cbc6c6 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 25 Aug 2020 23:57:19 +0700 Subject: [PATCH 08/14] remove the local static for seq values for tone --- cores/nRF5/Tone.cpp | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index df33e34f..b4b44113 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -170,23 +170,23 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) { // limit frequency to reasonable audible range if((frequency < 20) | (frequency > 25000)) { - LOG_LV1("TON", "frequency outside range [20..25000] -- ignoring"); + LOG_LV1("Tone", "frequency outside range [20..25000] -- ignoring"); return; } uint64_t pulse_count = _calculate_pulse_count(frequency, duration); uint16_t time_period = _calculate_time_period(frequency); if (!_pwm_config.ensurePwmPeripheralOwnership()) { - LOG_LV1("TON", "Unable to acquire PWM peripheral"); + LOG_LV1("Tone", "Unable to acquire PWM peripheral"); } else if (!_pwm_config.stopPlayback()) { - LOG_LV1("TON", "Unable to stop playback"); + LOG_LV1("Tone", "Unable to stop playback"); } else if (!_pwm_config.initializeFromPulseCountAndTimePeriod(pulse_count, time_period)) { - LOG_LV1("TON", "Failed calculating configuration"); + LOG_LV1("Tone", "Failed calculating configuration"); } else if (!_pwm_config.applyConfiguration(pin)) { - LOG_LV1("TON", "Failed applying configuration"); + LOG_LV1("Tone", "Failed applying configuration"); } else if (!_pwm_config.startPlayback()) { - LOG_LV1("TON", "Failed attempting to start PWM peripheral"); + LOG_LV1("Tone", "Failed attempting to start PWM peripheral"); } else { - //LOG_LV2("TON", "Started playback of tone at frequency %d duration %ld", frequency, duration); + //LOG_LV2("Tone", "Started playback of tone at frequency %d duration %ld", frequency, duration); } return; } @@ -199,7 +199,7 @@ void noTone(uint8_t pin) bool TonePwmConfig::ensurePwmPeripheralOwnership(void) { if (!_HwPWM->isOwner(TonePwmConfig::toneToken) && !_HwPWM->takeOwnership(TonePwmConfig::toneToken)) { - LOG_LV1("TON", "unable to allocate PWM2 to Tone"); + LOG_LV1("Tone", "unable to allocate PWM2 to Tone"); return false; } return true; @@ -238,7 +238,7 @@ bool TonePwmConfig::ensurePwmPeripheralOwnership(void) { bool TonePwmConfig::initializeFromPulseCountAndTimePeriod(uint64_t pulse_count_x, uint16_t time_period) { if (_bits_used(pulse_count_x) > 37) { - LOG_LV1("TON", "pulse count is limited to 37 bit long value"); + LOG_LV1("Tone", "pulse count is limited to 37 bit long value"); return false; } @@ -332,14 +332,8 @@ bool TonePwmConfig::applyConfiguration(uint32_t pin) { nrf_pwm_shorts_set(_PWMInstance, this->shorts); nrf_pwm_int_set(_PWMInstance, 0); - // static sequence value ... This is the value actually used - // during playback ... do NOT modify without semaphore *and* - // having ensured playback has stopped! - static uint16_t seq_values; // static value - seq_values = this->duty_with_polarity; - - nrf_pwm_seq_ptr_set(_PWMInstance, 0, &seq_values); - nrf_pwm_seq_ptr_set(_PWMInstance, 1, &seq_values); + nrf_pwm_seq_ptr_set(_PWMInstance, 0, &this->duty_with_polarity); + nrf_pwm_seq_ptr_set(_PWMInstance, 1, &this->duty_with_polarity); nrf_pwm_seq_cnt_set(_PWMInstance, 0, 1); nrf_pwm_seq_cnt_set(_PWMInstance, 1, 1); @@ -361,7 +355,7 @@ bool TonePwmConfig::applyConfiguration(uint32_t pin) { bool TonePwmConfig::startPlayback(void) { if (!this->ensurePwmPeripheralOwnership()) { - LOG_LV1("TON", "PWM peripheral not available for playback"); + LOG_LV1("Tone", "PWM peripheral not available for playback"); return false; } nrf_pwm_task_trigger(_PWMInstance, this->task_to_start); @@ -371,7 +365,7 @@ bool TonePwmConfig::startPlayback(void) { bool TonePwmConfig::stopPlayback(bool releaseOwnership) { if (!_HwPWM->isOwner(TonePwmConfig::toneToken)) { - LOG_LV2("TON", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); + LOG_LV2("Tone", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); return false; } // ensure stopped and then disable From 6f2adf4f62472e733e57b94a681fd1d728e54e12 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 01:22:35 +0700 Subject: [PATCH 09/14] 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; } From 3cc5b5ba73de382e622d55acc650b040223d2767 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 15:28:38 +0700 Subject: [PATCH 10/14] revert to use C11 atomic which is implemented by LDREX/STREX on M4 --- cores/nRF5/HardwarePWM.cpp | 23 +++++------------------ cores/nRF5/HardwarePWM.h | 3 ++- 2 files changed, 7 insertions(+), 19 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index b6e742ac..47c59a86 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -287,15 +287,9 @@ bool HardwarePWM::takeOwnership(uintptr_t token) if ( this->usedChannelCount() != 0 ) return false; if ( this->enabled() ) return false; - // This function must not be called within ISR - taskENTER_CRITICAL(); - if ( this->_owner_token == 0 ) - { - _owner_token = token; - } - taskEXIT_CRITICAL(); - - return _owner_token == token; + // Use C++11 atomic CAS operation + uintptr_t expectedValue = 0U; + return this->_owner_token.compare_exchange_strong(expectedValue, token); } // returns true ONLY when (1) no PWM channel has a pin attached, and (2) the owner token matches @@ -321,13 +315,6 @@ bool HardwarePWM::releaseOwnership(uintptr_t token) return false; // if it's enabled, do not allow ownership to be released, even with no pins in use } - // This function must not be called within ISR - taskENTER_CRITICAL(); - if ( this->_owner_token == token ) - { - _owner_token = 0; - } - taskEXIT_CRITICAL(); - - return _owner_token == 0; + // Use C++11 atomic CAS operation + return this->_owner_token.compare_exchange_strong(token, 0U); } diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index 188c6889..55623bf5 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -38,6 +38,7 @@ #include "common_inc.h" #include "nrf.h" +#include #ifdef NRF52840_XXAA #define HWPWM_MODULE_NUM 4 @@ -50,7 +51,7 @@ class HardwarePWM private: enum { MAX_CHANNELS = 4 }; // Max channel per group NRF_PWM_Type * const _pwm; - uintptr_t _owner_token; + std::atomic_uintptr_t _owner_token; uint16_t _seq0[MAX_CHANNELS]; From 13a01fe7a86725b28c7e2108d335905286eccf3e Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 15:41:47 +0700 Subject: [PATCH 11/14] change token type from uintptr_t to uint32_t --- cores/nRF5/HardwarePWM.cpp | 12 ++++++------ cores/nRF5/HardwarePWM.h | 8 ++++---- cores/nRF5/Tone.cpp | 2 +- cores/nRF5/wiring_analog.cpp | 2 +- libraries/Servo/src/nrf52/Servo.cpp | 2 +- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 47c59a86..d2ad8e5b 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -54,10 +54,10 @@ HardwarePWM* HwPWMx[] = }; #if CFG_DEBUG -bool can_stringify_token(uintptr_t token) +bool can_stringify_token(uint32_t token) { uint8_t * t = (uint8_t *)&token; - for (size_t i = 0; i < sizeof(uintptr_t); ++i, ++t) + for (size_t i = 0; i < sizeof(uint32_t); ++i, ++t) { uint8_t x = *t; if ((x < 0x20) || (x > 0x7E)) return false; @@ -71,7 +71,7 @@ void HardwarePWM::DebugOutput(Stream& logger) logger.printf("HwPWM Debug:"); for (size_t i = 0; i < count; i++) { HardwarePWM const * pwm = HwPWMx[i]; - uintptr_t token = pwm->_owner_token; + uint32_t token = pwm->_owner_token; logger.printf(" || %d:", i); if (can_stringify_token(token)) { uint8_t * t = (uint8_t*)(&token); @@ -271,7 +271,7 @@ uint8_t HardwarePWM::freeChannelCount(void) const } // returns true ONLY when (1) no PWM channel has a pin, and (2) the owner token is nullptr -bool HardwarePWM::takeOwnership(uintptr_t token) +bool HardwarePWM::takeOwnership(uint32_t token) { if (token == 0) { LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in takeOwnership)"); @@ -288,12 +288,12 @@ bool HardwarePWM::takeOwnership(uintptr_t token) if ( this->enabled() ) return false; // Use C++11 atomic CAS operation - uintptr_t expectedValue = 0U; + uint32_t expectedValue = 0U; return this->_owner_token.compare_exchange_strong(expectedValue, 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) +bool HardwarePWM::releaseOwnership(uint32_t token) { if (token == 0) { LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in releaseOwnership)"); diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index 55623bf5..47ec16c5 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -51,7 +51,7 @@ class HardwarePWM private: enum { MAX_CHANNELS = 4 }; // Max channel per group NRF_PWM_Type * const _pwm; - std::atomic_uintptr_t _owner_token; + std::atomic_uint32_t _owner_token; uint16_t _seq0[MAX_CHANNELS]; @@ -70,13 +70,13 @@ class HardwarePWM // 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); + bool takeOwnership (uint32_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); + bool releaseOwnership(uint32_t token); // allows caller to verify that they own the peripheral - bool isOwner(uintptr_t token) const + bool isOwner(uint32_t token) const { return this->_owner_token == token; } diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index b4b44113..b29a6ddd 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -48,7 +48,7 @@ static HardwarePWM * const _HwPWM = HwPWMx[2]; // Defined a struct, to simplify validation testing ... also provides context when debugging class TonePwmConfig { private: - const uintptr_t toneToken = 0x656e6f54; //< 'T' 'o' 'n' 'e' + const uint32_t toneToken = 0x656e6f54; //< 'T' 'o' 'n' 'e' uint64_t pulse_count; //< total number of PWM pulses uint32_t seq0_refresh; //< count of pulses for each SEQ0 iteration uint32_t seq1_refresh; //< count of pulses for each SEQ1 iteration diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 93c78fbb..7065b89a 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -47,7 +47,7 @@ extern "C" { static uint8_t _analogResolution = 8; // default is 256 levels -static uintptr_t _analogToken = 0x676f6c41; // 'A' 'l' 'o' 'g' +static uint32_t _analogToken = 0x676f6c41; // 'A' 'l' 'o' 'g' /** * This will apply to all PWM Hardware currently used by analogWrite(), diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp index 506a9519..015bddf5 100644 --- a/libraries/Servo/src/nrf52/Servo.cpp +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -21,7 +21,7 @@ #include #include -static uintptr_t _servoToken = 0x76726553; // 'S' 'e' 'r' 'v' +static uint32_t _servoToken = 0x76726553; // 'S' 'e' 'r' 'v' static servo_t servos[MAX_SERVOS]; // static array of servo structures uint8_t ServoCount = 0; // the total number of attached servos From 786ceae1f1d48ed61758766064bec3b1c253c646 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 15:45:16 +0700 Subject: [PATCH 12/14] change token from const var to enum --- cores/nRF5/Tone.cpp | 8 ++++---- cores/nRF5/wiring_analog.cpp | 14 +++++++++----- libraries/Servo/src/nrf52/Servo.cpp | 11 +++++++---- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index b29a6ddd..e1569a7a 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -48,7 +48,7 @@ static HardwarePWM * const _HwPWM = HwPWMx[2]; // Defined a struct, to simplify validation testing ... also provides context when debugging class TonePwmConfig { private: - const uint32_t toneToken = 0x656e6f54; //< 'T' 'o' 'n' 'e' + enum { TONE_TOKEN = 0x656e6f54 }; //< 'T' 'o' 'n' 'e' uint64_t pulse_count; //< total number of PWM pulses uint32_t seq0_refresh; //< count of pulses for each SEQ0 iteration uint32_t seq1_refresh; //< count of pulses for each SEQ1 iteration @@ -198,7 +198,7 @@ void noTone(uint8_t pin) } bool TonePwmConfig::ensurePwmPeripheralOwnership(void) { - if (!_HwPWM->isOwner(TonePwmConfig::toneToken) && !_HwPWM->takeOwnership(TonePwmConfig::toneToken)) { + if (!_HwPWM->isOwner(TonePwmConfig::TONE_TOKEN) && !_HwPWM->takeOwnership(TonePwmConfig::TONE_TOKEN)) { LOG_LV1("Tone", "unable to allocate PWM2 to Tone"); return false; } @@ -364,7 +364,7 @@ bool TonePwmConfig::startPlayback(void) { bool TonePwmConfig::stopPlayback(bool releaseOwnership) { - if (!_HwPWM->isOwner(TonePwmConfig::toneToken)) { + if (!_HwPWM->isOwner(TonePwmConfig::TONE_TOKEN)) { LOG_LV2("Tone", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); return false; } @@ -376,7 +376,7 @@ bool TonePwmConfig::stopPlayback(bool releaseOwnership) { } if (releaseOwnership) { - _HwPWM->releaseOwnership(TonePwmConfig::toneToken); + _HwPWM->releaseOwnership(TonePwmConfig::TONE_TOKEN); } return true; diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 7065b89a..38fefdf1 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -46,8 +46,12 @@ extern "C" { +enum +{ + ANALOG_TOKEN = 0x676f6c41 // 'A' 'l' 'o' 'g' +}; + static uint8_t _analogResolution = 8; // default is 256 levels -static uint32_t _analogToken = 0x676f6c41; // 'A' 'l' 'o' 'g' /** * This will apply to all PWM Hardware currently used by analogWrite(), @@ -59,7 +63,7 @@ void analogWriteResolution( uint8_t res ) _analogResolution = res; for (int i = 0; iisOwner(_analogToken)) + if (HwPWMx[i]->isOwner(ANALOG_TOKEN)) { HwPWMx[i]->setResolution(res); } @@ -78,7 +82,7 @@ void analogWrite( uint32_t pin, uint32_t value ) // first, handle the case where the pin is already in use by analogWrite() for(int i=0; iisOwner(_analogToken)) + if (HwPWMx[i]->isOwner(ANALOG_TOKEN)) { int const ch = HwPWMx[i]->pin2channel(pin); if (ch >= 0) @@ -92,7 +96,7 @@ void analogWrite( uint32_t pin, uint32_t value ) // Next, handle the case where can add the pin to a PWM instance already owned by analogWrite() for(int i=0; iisOwner(_analogToken) && HwPWMx[i]->addPin(pin) ) + if ( HwPWMx[i]->isOwner(ANALOG_TOKEN) && HwPWMx[i]->addPin(pin) ) { // successfully added the pin, so write the value also HwPWMx[i]->writePin(pin, value); @@ -106,7 +110,7 @@ void analogWrite( uint32_t pin, uint32_t value ) // 2. it currently has no pins in use. for(int i=0; itakeOwnership(_analogToken)) + if (HwPWMx[i]->takeOwnership(ANALOG_TOKEN)) { // apply the cached analog resolution to newly owned instances HwPWMx[i]->setResolution(_analogResolution); diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp index 015bddf5..e83b97cb 100644 --- a/libraries/Servo/src/nrf52/Servo.cpp +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -21,7 +21,10 @@ #include #include -static uint32_t _servoToken = 0x76726553; // 'S' 'e' 'r' 'v' +enum +{ + SERVO_TOKEN = 0x76726553 // 'S' 'e' 'r' 'v' +}; static servo_t servos[MAX_SERVOS]; // static array of servo structures uint8_t ServoCount = 0; // the total number of attached servos @@ -71,7 +74,7 @@ uint8_t Servo::attach(int pin, int min, int max) // first, use existing HWPWM modules (already owned by Servo) for ( int i = 0; i < HWPWM_MODULE_NUM; i++ ) { - if ( HwPWMx[i]->isOwner(_servoToken) && HwPWMx[i]->addPin(pin) ) + if ( HwPWMx[i]->isOwner(SERVO_TOKEN) && HwPWMx[i]->addPin(pin) ) { this->pwm = HwPWMx[i]; succeeded = true; @@ -84,7 +87,7 @@ uint8_t Servo::attach(int pin, int min, int max) { for ( int i = 0; i < HWPWM_MODULE_NUM; i++ ) { - if ( HwPWMx[i]->takeOwnership(_servoToken) && HwPWMx[i]->addPin(pin) ) + if ( HwPWMx[i]->takeOwnership(SERVO_TOKEN) && HwPWMx[i]->addPin(pin) ) { this->pwm = HwPWMx[i]; succeeded = true; @@ -124,7 +127,7 @@ void Servo::detach() pwm->removePin(pin); if (pwm->usedChannelCount() == 0) { pwm->stop(); // disables peripheral so can release ownership - pwm->releaseOwnership(_servoToken); + pwm->releaseOwnership(SERVO_TOKEN); } } From ddd33583897db9b34ca6f8d03c5a25e0a41bd121 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 16:02:39 +0700 Subject: [PATCH 13/14] revert checking for inISR before logging --- cores/nRF5/HardwarePWM.cpp | 13 +++++++------ cores/nRF5/Tone.cpp | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index d2ad8e5b..34719619 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -273,13 +273,14 @@ uint8_t HardwarePWM::freeChannelCount(void) const // returns true ONLY when (1) no PWM channel has a pin, and (2) the owner token is nullptr bool HardwarePWM::takeOwnership(uint32_t token) { + if (token == 0) { - LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in takeOwnership)"); + if (!isInISR()) LOG_LV1("HwPWM", "zero is not a valid ownership token (attempted use in takeOwnership)"); return false; } if (token == this->_owner_token) { - LOG_LV1("HwPWM", "failing to acquire ownership because already owned by requesting token (cannot take ownership twice)"); + if (!isInISR()) LOG_LV1("HwPWM", "failing to acquire ownership because already owned by requesting token (cannot take ownership twice)"); return false; } @@ -296,22 +297,22 @@ bool HardwarePWM::takeOwnership(uint32_t token) bool HardwarePWM::releaseOwnership(uint32_t token) { if (token == 0) { - LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in releaseOwnership)"); + if (!isInISR()) LOG_LV1("HwPWM", "zero is not a valid ownership token (attempted use in releaseOwnership)"); return false; } if (!this->isOwner(token)) { - LOG_LV1("HwPWM", "attempt to release ownership when not the current owner"); + if (!isInISR()) LOG_LV1("HwPWM", "attempt to release ownership when not the current owner"); return false; } if (this->usedChannelCount() != 0) { - LOG_LV1("HwPWM", "attempt to release ownership when at least on channel is still connected"); + if (!isInISR()) LOG_LV1("HwPWM", "attempt to release ownership when at least on channel is still connected"); return false; } if (this->enabled()) { - LOG_LV1("HwPWM", "attempt to release ownership when PWM peripheral is still enabled"); + if (!isInISR()) LOG_LV1("HwPWM", "attempt to release ownership when PWM peripheral is still enabled"); return false; // if it's enabled, do not allow ownership to be released, even with no pins in use } diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index e1569a7a..9a15fb0f 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -177,7 +177,7 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) uint16_t time_period = _calculate_time_period(frequency); if (!_pwm_config.ensurePwmPeripheralOwnership()) { LOG_LV1("Tone", "Unable to acquire PWM peripheral"); - } else if (!_pwm_config.stopPlayback()) { + } else if (!_pwm_config.stopPlayback(false)) { LOG_LV1("Tone", "Unable to stop playback"); } else if (!_pwm_config.initializeFromPulseCountAndTimePeriod(pulse_count, time_period)) { LOG_LV1("Tone", "Failed calculating configuration"); From b2c9e54358e46430b913c0852876f94a2601b3b5 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 17:18:33 +0700 Subject: [PATCH 14/14] clean up --- cores/nRF5/HardwarePWM.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 34719619..17768ad0 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -273,14 +273,15 @@ uint8_t HardwarePWM::freeChannelCount(void) const // returns true ONLY when (1) no PWM channel has a pin, and (2) the owner token is nullptr bool HardwarePWM::takeOwnership(uint32_t token) { + bool const thread_mode = !isInISR(); if (token == 0) { - if (!isInISR()) LOG_LV1("HwPWM", "zero is not a valid ownership token (attempted use in takeOwnership)"); + if (thread_mode) LOG_LV1("HwPWM", "zero is not a valid ownership token (attempted use in takeOwnership)"); return false; } if (token == this->_owner_token) { - if (!isInISR()) LOG_LV1("HwPWM", "failing to acquire ownership because already owned by requesting token (cannot take ownership twice)"); + if (thread_mode) LOG_LV1("HwPWM", "failing to acquire ownership because already owned by requesting token (cannot take ownership twice)"); return false; } @@ -296,23 +297,25 @@ bool HardwarePWM::takeOwnership(uint32_t token) // returns true ONLY when (1) no PWM channel has a pin attached, and (2) the owner token matches bool HardwarePWM::releaseOwnership(uint32_t token) { + bool const thread_mode = !isInISR(); + if (token == 0) { - if (!isInISR()) LOG_LV1("HwPWM", "zero is not a valid ownership token (attempted use in releaseOwnership)"); + if (thread_mode) LOG_LV1("HwPWM", "zero is not a valid ownership token (attempted use in releaseOwnership)"); return false; } if (!this->isOwner(token)) { - if (!isInISR()) LOG_LV1("HwPWM", "attempt to release ownership when not the current owner"); + if (thread_mode) LOG_LV1("HwPWM", "attempt to release ownership when not the current owner"); return false; } if (this->usedChannelCount() != 0) { - if (!isInISR()) LOG_LV1("HwPWM", "attempt to release ownership when at least on channel is still connected"); + if (thread_mode) LOG_LV1("HwPWM", "attempt to release ownership when at least on channel is still connected"); return false; } if (this->enabled()) { - if (!isInISR()) LOG_LV1("HwPWM", "attempt to release ownership when PWM peripheral is still enabled"); + if (thread_mode) LOG_LV1("HwPWM", "attempt to release ownership when PWM peripheral is still enabled"); return false; // if it's enabled, do not allow ownership to be released, even with no pins in use }