From 73fb5887f5ee040a159c868dee7886221a4e1ec7 Mon Sep 17 00:00:00 2001 From: Trevor Date: Tue, 14 Jul 2020 15:45:34 -0600 Subject: [PATCH 01/76] Added I2C pin configuration To configure the I2C pins call Wire.setPins(SDA_Pin, SCL_pin) prior to Wire.begin() --- libraries/Wire/Wire.h | 1 + libraries/Wire/Wire_nRF52.cpp | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/libraries/Wire/Wire.h b/libraries/Wire/Wire.h index ba993d1c..0c65a00c 100755 --- a/libraries/Wire/Wire.h +++ b/libraries/Wire/Wire.h @@ -39,6 +39,7 @@ class TwoWire : public Stream void begin(uint8_t); void end(); void setClock(uint32_t); + void setPins(uint8_t pin_SDA, uint8_t pin_SCL); void beginTransmission(uint8_t); uint8_t endTransmission(bool stopBit); diff --git a/libraries/Wire/Wire_nRF52.cpp b/libraries/Wire/Wire_nRF52.cpp index 39043059..81b9564b 100755 --- a/libraries/Wire/Wire_nRF52.cpp +++ b/libraries/Wire/Wire_nRF52.cpp @@ -127,6 +127,12 @@ void TwoWire::setClock(uint32_t baudrate) { } } +void TwoWire::setPins(uint8_t pin_SDA, uint8_t pin_SCL) +{ + this->_uc_pinSDA = g_ADigitalPinMap[pin_SDA]; + this->_uc_pinSCL = g_ADigitalPinMap[pin_SCL]; +} + void TwoWire::end() { if (master) { From 2981565830fb132353fb4399daec353aae64acbb Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 12 Apr 2020 15:15:04 -0700 Subject: [PATCH 02/76] Remove dead code --- cores/nRF5/wiring_analog_nRF52.c | 42 -------------------------------- 1 file changed, 42 deletions(-) diff --git a/cores/nRF5/wiring_analog_nRF52.c b/cores/nRF5/wiring_analog_nRF52.c index ee95d318..9c33c608 100644 --- a/cores/nRF5/wiring_analog_nRF52.c +++ b/cores/nRF5/wiring_analog_nRF52.c @@ -273,48 +273,6 @@ uint32_t analogRead( uint32_t ulPin ) return mapResolution(value, resolution, readResolution); } -#if 0 -// Right now, PWM output only works on the pins with -// hardware support. These are defined in the appropriate -// pins_*.c file. For the rest of the pins, we default -// to digital output. -void analogWrite( uint32_t ulPin, uint32_t ulValue ) -{ - if (ulPin >= PINS_COUNT) { - return; - } - - ulPin = g_ADigitalPinMap[ulPin]; - - for (int i = 0; i < PWM_COUNT; i++) { - if (pwmChannelPins[i] == 0xFFFFFFFF || pwmChannelPins[i] == ulPin) { - pwmChannelPins[i] = ulPin; - pwmChannelSequence[i] = bit(15) | ulValue; - - NRF_PWM_Type* pwm = pwms[i]; - - pwm->PSEL.OUT[0] = ulPin; - pwm->PSEL.OUT[1] = ulPin; - pwm->PSEL.OUT[2] = ulPin; - pwm->PSEL.OUT[3] = ulPin; - pwm->ENABLE = (PWM_ENABLE_ENABLE_Enabled << PWM_ENABLE_ENABLE_Pos); - pwm->PRESCALER = PWM_PRESCALER_PRESCALER_DIV_1; - pwm->MODE = PWM_MODE_UPDOWN_Up; - pwm->COUNTERTOP = (1 << writeResolution) - 1; - pwm->LOOP = 0; - pwm->DECODER = ((uint32_t)PWM_DECODER_LOAD_Common << PWM_DECODER_LOAD_Pos) | ((uint32_t)PWM_DECODER_MODE_RefreshCount << PWM_DECODER_MODE_Pos); - pwm->SEQ[0].PTR = (uint32_t)&pwmChannelSequence[i]; - pwm->SEQ[0].CNT = 1; - pwm->SEQ[0].REFRESH = 1; - pwm->SEQ[0].ENDDELAY = 0; - pwm->TASKS_SEQSTART[0] = 0x1UL; - - break; - } - } -} -#endif - #ifdef __cplusplus } #endif From b4d777f7f329ac5d8c65e42bc21702f15ed8a8f7 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 12 Apr 2020 17:20:03 -0700 Subject: [PATCH 03/76] Expose API for count of used/free channels --- cores/nRF5/HardwarePWM.cpp | 18 ++++++++++++++++++ cores/nRF5/HardwarePWM.h | 4 ++++ 2 files changed, 22 insertions(+) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 881c054d..9caaa860 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -218,3 +218,21 @@ uint16_t HardwarePWM::readChannel(uint8_t ch) return (_seq0[ch] & 0x7FFF); } +uint8_t HardwarePWM::usedChannelCount(void) +{ + uint8_t usedChannels = 0; + for(int i=0; iPSEL.OUT[i] & PWM_PSEL_OUT_CONNECT_Msk ) + { + usedChannels++; + } + } + return usedChannels; +} + +uint8_t HardwarePWM::freeChannelCount(void) +{ + return MAX_CHANNELS - usedChannelCount(); +} + diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index bf2691e3..eaccff1f 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -96,6 +96,10 @@ class HardwarePWM // Read current set value uint16_t readPin (uint8_t pin); uint16_t readChannel (uint8_t ch); + + // Get count of used / free channels + uint8_t usedChannelCount(); + uint8_t freeChannelCount(); }; extern HardwarePWM HwPWM0; From af680357dd68eeb9da44d7da9e40febd485df454 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 12 Apr 2020 17:24:23 -0700 Subject: [PATCH 04/76] analogWrite() avoids hostile takeover of PWM peripherals --- cores/nRF5/wiring_analog.cpp | 66 +++++++++++++++++++++++++++++++----- 1 file changed, 58 insertions(+), 8 deletions(-) diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 570be9eb..c15e459e 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -45,13 +45,30 @@ extern "C" { +class INTERNAL_ANALOG_STATE { + public: + uint8_t _lastAnalogWriteResolution = 8; // default value is 8-bit resolution (0..255) + uint8_t _moduleUsedByAnalogWrites[HWPWM_MODULE_NUM]; + INTERNAL_ANALOG_STATE() : _lastAnalogWriteResolution(8) { + for (int i = 0; i < HWPWM_MODULE_NUM; i++) { + _moduleUsedByAnalogWrites[i] = 0; + } + } +}; + +static INTERNAL_ANALOG_STATE _AnalogState; + /** - * This will apply to all PWM Hardware + * This will apply to all PWM Hardware currently used by analogWrite(), + * and automatically apply to future calls to analogWrite(). */ void analogWriteResolution( uint8_t res ) { + // save the resolution for when adding a new instance + _AnalogState._lastAnalogWriteResolution = res; for (int i = 0; isetResolution(res); } } @@ -65,17 +82,50 @@ 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 attempt to find the pin in any of the HWPWM modules used for analog writes for(int i=0; iaddPin(pin) ) - { - HwPWMx[i]->writePin(pin, value); - return; - } + if (!_AnalogState._moduleUsedByAnalogWrites[i]) continue; + int const ch = HwPWMx[i]->pin2channel(pin); + if (ch < 0) continue; // pin not in use by the PWM instance + // already in use by this PWM instance as channel ch ... + HwPWMx[i]->writeChannel(ch, value); + return; } + + // Next try adding only to those modules that are already in use + for(int i=0; iaddPin(pin)) continue; + // added to an already-used PWM instance, so write the value + HwPWMx[i]->writePin(pin, value); + return; + } + + // Attempt to acquire a new HwPWMx instance ... but only where + // 1. it's not one already used for analog, and + // 2. it currently has no pins in use. + for(int i=0; iusedChannelCount() != 0) continue; + // added to an already-used PWM instance, so write the value + HwPWMx[i]->setResolution(_AnalogState._lastAnalogWriteResolution); + HwPWMx[i]->writePin(pin, value); + 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 + return; } -} +} // end extern "C" From a771af3ed6f6b5d0397ab170c85b5ae7a3cbfaf6 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 12 Apr 2020 17:35:04 -0700 Subject: [PATCH 05/76] remove dead code --- cores/nRF5/wiring_analog_nRF52.c | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/cores/nRF5/wiring_analog_nRF52.c b/cores/nRF5/wiring_analog_nRF52.c index 9c33c608..b8a50fc5 100644 --- a/cores/nRF5/wiring_analog_nRF52.c +++ b/cores/nRF5/wiring_analog_nRF52.c @@ -33,38 +33,14 @@ static uint32_t saadcGain = SAADC_CH_CONFIG_GAIN_Gain1_6; static bool saadcBurst = SAADC_CH_CONFIG_BURST_Disabled; -#if 0 // Note: Adafruit use seperated HardwarePWM class -#define PWM_COUNT 3 - -static NRF_PWM_Type* pwms[PWM_COUNT] = { - NRF_PWM0, - NRF_PWM1, - NRF_PWM2 -}; - -static uint32_t pwmChannelPins[PWM_COUNT] = { - 0xFFFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFF -}; -static uint16_t pwmChannelSequence[PWM_COUNT]; -#endif +// Note: Adafruit use seperated HardwarePWM class static int readResolution = 10; -//static int writeResolution = 8; - void analogReadResolution( int res ) { readResolution = res; } -#if 0 -void analogWriteResolution( int res ) -{ - writeResolution = res; -} -#endif - static inline uint32_t mapResolution( uint32_t value, uint32_t from, uint32_t to ) { if ( from == to ) From ab1b90490c2fe5b2ae444a490ff2f43c83e6eb87 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 26 Apr 2020 02:27:38 -0700 Subject: [PATCH 06/76] 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); From d469728574ec3c7318dbbccd70607ac787c7ea7e Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Mon, 27 Apr 2020 00:58:04 -0700 Subject: [PATCH 07/76] Use HwPWM ownership abstraction --- cores/nRF5/common_func.h | 10 ++++++ cores/nRF5/wiring_analog.cpp | 68 +++++++++++++++++++++--------------- 2 files changed, 50 insertions(+), 28 deletions(-) diff --git a/cores/nRF5/common_func.h b/cores/nRF5/common_func.h index 60c7cf0d..c6229b8a 100644 --- a/cores/nRF5/common_func.h +++ b/cores/nRF5/common_func.h @@ -73,6 +73,8 @@ #define ADA_COUNTER __LINE__ #endif +#include + #define COMMENT_OUT(x) #define memclr(buffer, size) memset(buffer, 0, size) @@ -170,6 +172,14 @@ const char* dbg_err_str(int32_t err_id); // TODO move to other place #define LOG_LV2_BUFFER(...) #endif +#if CFG_DEBUG >= 3 +#define LOG_LV3(...) ADALOG(__VA_ARGS__) +#define LOG_LV3_BUFFER(...) ADALOG_BUFFER(__VA_ARGS__) +#else +#define LOG_LV3(...) +#define LOG_LV3_BUFFER(...) +#endif + #if CFG_DEBUG #define PRINT_LOCATION() PRINTF("%s: %d:\n", __PRETTY_FUNCTION__, __LINE__) diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index c15e459e..e7d7b2f4 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -36,6 +36,7 @@ #include "Arduino.h" + /* Implement analogWrite() and analogWriteResolution() using * HardwarePWM. * @@ -45,18 +46,8 @@ extern "C" { -class INTERNAL_ANALOG_STATE { - public: - uint8_t _lastAnalogWriteResolution = 8; // default value is 8-bit resolution (0..255) - uint8_t _moduleUsedByAnalogWrites[HWPWM_MODULE_NUM]; - INTERNAL_ANALOG_STATE() : _lastAnalogWriteResolution(8) { - for (int i = 0; i < HWPWM_MODULE_NUM; i++) { - _moduleUsedByAnalogWrites[i] = 0; - } - } -}; - -static INTERNAL_ANALOG_STATE _AnalogState; +static uint8_t _lastAnalogWriteResolution; +static const uintptr_t _token = (uintptr_t)(&_lastAnalogWriteResolution); /** * This will apply to all PWM Hardware currently used by analogWrite(), @@ -65,10 +56,10 @@ static INTERNAL_ANALOG_STATE _AnalogState; void analogWriteResolution( uint8_t res ) { // save the resolution for when adding a new instance - _AnalogState._lastAnalogWriteResolution = res; + _lastAnalogWriteResolution = res; for (int i = 0; iisOwner(_token)) continue; HwPWMx[i]->setResolution(res); } } @@ -82,26 +73,42 @@ 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 + /* 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 attempt to find the pin in any of the HWPWM modules used for analog writes + // first, handle the case where the pin is already in use by analogWrite() for(int i=0; iisOwner(_token)) { + LOG_LV3("ANA", "not currently owner of PWM %d", i); + continue; // skip if not owner of this PWM instance + } + int const ch = HwPWMx[i]->pin2channel(pin); - if (ch < 0) continue; // pin not in use by the PWM instance - // already in use by this PWM instance as channel ch ... + if (ch < 0) { + LOG_LV3("ANA", "pin %d is not used by PWM %d", pin, i); + continue; // pin not in use by this PWM instance + } + LOG_LV2("ANA", "updating pin %" PRIu32 " used by PWM %d", pin, i); HwPWMx[i]->writeChannel(ch, value); return; } - // Next try adding only to those modules that are already in use + // Next, handle the case where can add the pin to a PWM instance already owned by analogWrite() for(int i=0; iaddPin(pin)) continue; - // added to an already-used PWM instance, so write the value + if (!HwPWMx[i]->isOwner(_token)) { + LOG_LV3("ANA", "not currently owner of PWM %d", i); + continue; + } + if (!HwPWMx[i]->addPin(pin)) { + LOG_LV3("ANA", "could not add pin %" PRIu32 " to PWM %d", pin, i); + 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; } @@ -111,11 +118,16 @@ void analogWrite( uint32_t pin, uint32_t value ) // 2. it currently has no pins in use. for(int i=0; iusedChannelCount() != 0) continue; - // added to an already-used PWM instance, so write the value - HwPWMx[i]->setResolution(_AnalogState._lastAnalogWriteResolution); + if (!HwPWMx[i]->takeOwnership(_token)) { + LOG_LV3("ANA", "Could not take ownership of PWM %d", i); + continue; + } + + // apply the cached analog resolution to newly owned instances + HwPWMx[i]->setResolution(_lastAnalogWriteResolution); + 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; } From d5dc053a34a4f2e83f4c3d98f0fbafb53302b510 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Fri, 1 May 2020 16:42:25 -0700 Subject: [PATCH 08/76] Use HwPWM ownership abstraction --- cores/nRF5/Tone.cpp | 59 +++++++++++++++++++++++++++++++++------------ 1 file changed, 43 insertions(+), 16 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index e244d391..20def523 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -34,35 +34,54 @@ Version Modified By Date Comments 0010 Arduino.org 16/07/27 Added Arduino Primo support *************************************************/ - +#include "Arduino.h" #include "Tone.h" #include "WVariant.h" unsigned long int count_duration=0; volatile bool no_stop = false; uint8_t pin_sound=0; +static uintptr_t _toneToken = (uintptr_t)(&_toneToken); void tone(uint8_t pin, unsigned int frequency, unsigned long duration) { + static_assert(sizeof(unsigned long) == sizeof(uint32_t)); + unsigned int time_per=0; - - if((frequency < 20) | (frequency > 25000)) return; - + + // limit frequency to reasonable audible range + if((frequency < 20) | (frequency > 25000)) { + LOG_LV1("TON", "frequency outside range [20..25000] -- ignoring"); + return; + } + + // Use fixed PWM2 (due to need to connect interrupt) + if (!HwPWMx[2]->isOwner(_toneToken) && + !HwPWMx[2]->takeOwnership(_toneToken)) { + LOG_LV1("TON", "unable to allocate PWM2 to Tone"); + return; + } float per=float(1)/frequency; time_per=per/0.000008; unsigned int duty=time_per/2; - if(duration > 0){ + if(duration > 0) { no_stop = false; float mil=float(duration)/1000; - if(per>mil) + if(per>mil) { count_duration=1; - else + } else { count_duration= mil/per; - } - else + } + } else { no_stop = true; + } + + // PWM configuration depends on the following: + // [ ] time_per + // [ ] duty ( via seq ) + // [ ] pin ( via pins[0] ) // Configure PWM static uint16_t seq_values[]={0}; @@ -97,6 +116,7 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) break; } #else + // Use fixed PWM2, TODO could conflict with other usage uint32_t pins[NRF_PWM_CHANNEL_COUNT]={NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}; pins[0] = g_ADigitalPinMap[pin]; @@ -110,7 +130,7 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) nrf_pwm_configure(PWMInstance, NRF_PWM_CLK_125kHz, NRF_PWM_MODE_UP, time_per); nrf_pwm_decoder_set(PWMInstance, NRF_PWM_LOAD_COMMON, NRF_PWM_STEP_AUTO); nrf_pwm_sequence_set(PWMInstance, 0, &seq); - nrf_pwm_shorts_enable(PWMInstance, NRF_PWM_SHORT_SEQEND0_STOP_MASK); + nrf_pwm_shorts_enable(PWMInstance, NRF_PWM_SHORT_SEQEND0_STOP_MASK); // shortcut for when SEQ0 ends, PWM output will automatically stop // enable interrupt nrf_pwm_event_clear(PWMInstance, NRF_PWM_EVENT_PWMPERIODEND); @@ -125,6 +145,11 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) void noTone(uint8_t pin) { + if (!HwPWMx[2]->isOwner(_toneToken)) { + LOG_LV1("TON", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); + return; + } + #if 0 uint8_t pwm_type=g_APinDescription[pin].ulPWMChannel; NRF_PWM_Type * PWMInstance = NRF_PWM0; @@ -180,13 +205,15 @@ void PWM2_IRQHandler(void){ nrf_pwm_event_clear(NRF_PWM2, NRF_PWM_EVENT_PWMPERIODEND); if(!no_stop){ count_duration--; - if(count_duration == 0) - noTone(pin_sound); - else - nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_SEQSTART0); - } - else + if(count_duration == 0) { + nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_STOP); + nrf_pwm_disable(NRF_PWM2); + } else { + nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_SEQSTART0); + } + } else { nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_SEQSTART0); + } } #ifdef __cplusplus From 3efce16900e7b16f048f2e1e55eddefaac6d4594 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 3 May 2020 19:39:45 -0700 Subject: [PATCH 09/76] Servo can also use HwPWM ownership abstraction --- libraries/Servo/src/Servo.h | 2 +- libraries/Servo/src/nrf52/Servo.cpp | 100 ++++++++++++++++++---------- 2 files changed, 66 insertions(+), 36 deletions(-) diff --git a/libraries/Servo/src/Servo.h b/libraries/Servo/src/Servo.h index 50979dfb..28df7462 100644 --- a/libraries/Servo/src/Servo.h +++ b/libraries/Servo/src/Servo.h @@ -101,7 +101,7 @@ class Servo { public: Servo(); - uint8_t attach(int pin); // attach the given pin to the next free channel, sets pinMode, returns channel number or 0 if failure + uint8_t attach(int pin); // attach the given pin to the next free channel, sets pinMode, returns channel number or INVALID_SERVO if failure (zero is a valid channel number) uint8_t attach(int pin, int min, int max); // as above but also sets min and max values for writes. void detach(); void write(int value); // if value is < 200 its treated as an angle, otherwise as pulse width in microseconds diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp index b9b86c02..5966873a 100644 --- a/libraries/Servo/src/nrf52/Servo.cpp +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -21,6 +21,7 @@ #include #include +static uintptr_t _servoToken = (uintptr_t)(&_servoToken); static servo_t servos[MAX_SERVOS]; // static array of servo structures uint8_t ServoCount = 0; // the total number of attached servos @@ -32,7 +33,6 @@ Servo::Servo() } else { this->servoIndex = INVALID_SERVO; // too many servos } - this->pwm = NULL; } @@ -43,55 +43,81 @@ uint8_t Servo::attach(int pin) uint8_t Servo::attach(int pin, int min, int max) { - if (this->servoIndex < MAX_SERVOS) { - pinMode(pin, OUTPUT); // set servo pin to output - servos[this->servoIndex].Pin.nbr = pin; + if (this->servoIndex == INVALID_SERVO) { + 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_RESOLUTIONmin = min; - this->max = max; + //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; + servos[this->servoIndex].Pin.isActive = true; - // Adafruit, add pin to 1 of available Hw PWM - for(int i=0; iaddPin(pin) ) - { + // 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)) { + 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)) { this->pwm = HwPWMx[i]; + succeeded = true; break; } } + } + if (succeeded) { // do not use this->pwm unless success above! this->pwm->setMaxValue(MAXVALUE); this->pwm->setClockDiv(CLOCKDIV); - } - return this->servoIndex; + return succeeded ? this->servoIndex : INVALID_SERVO; // return INVALID_SERVO on failure (zero is a valid servo index) } void Servo::detach() { + if (this->servoIndex == INVALID_SERVO) { + return; + } + uint8_t const pin = servos[this->servoIndex].Pin.nbr; - - servos[this->servoIndex].Pin.isActive = false; - - // remove pin from HW PWM - this->pwm->removePin(pin); + servos[this->servoIndex].Pin.isActive = false; + // remove pin from HW PWM + HardwarePWM * pwm = this->pwm; + this->pwm = nullptr; + pwm->removePin(pin); + pwm->releaseOwnership(_servoToken); // ignore failure ... which happens if a pin is still in use, for example } - void Servo::write(int value) -{ - if (value < 0) +{ + if (value < 0) { value = 0; - else if (value > 180) + } else if (value > 180) { value = 180; + } value = map(value, 0, 180, this->min, this->max); writeMicroseconds(value); @@ -100,9 +126,10 @@ void Servo::write(int value) void Servo::writeMicroseconds(int value) { - uint8_t pin = servos[this->servoIndex].Pin.nbr; - - if ( this->pwm ) this->pwm->writePin(pin, value/DUTY_CYCLE_RESOLUTION); + if (this->pwm) { // pwm is only set when this->servoIndex != INVALID_SERVO + uint8_t pin = servos[this->servoIndex].Pin.nbr; + this->pwm->writePin(pin, value/DUTY_CYCLE_RESOLUTION); + } } int Servo::read() // return the value as degrees @@ -112,15 +139,18 @@ int Servo::read() // return the value as degrees int Servo::readMicroseconds() { - uint8_t pin = servos[this->servoIndex].Pin.nbr; - - if ( this->pwm ) return this->pwm->readPin(pin)*DUTY_CYCLE_RESOLUTION; - + if (this->pwm) { // pwm is only set when this->servoIndex != INVALID_SERVO + uint8_t pin = servos[this->servoIndex].Pin.nbr; + return this->pwm->readPin(pin)*DUTY_CYCLE_RESOLUTION; + } return 0; } bool Servo::attached() { + if (this->servoIndex == INVALID_SERVO) { + return false; + } return servos[this->servoIndex].Pin.isActive; } From c58c01df68a395fb134759e44eb6fc7829e51b3b Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 3 May 2020 20:00:22 -0700 Subject: [PATCH 10/76] Add check for PWM being ENABLED --- cores/nRF5/HardwarePWM.cpp | 2 ++ libraries/Servo/src/nrf52/Servo.cpp | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 9169d9c4..fc8ceb00 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -58,6 +58,7 @@ 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 + if (this->enabled ) return false; // if it's enabled, do not allow new ownership, even with no pins 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); @@ -67,6 +68,7 @@ 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 + if ( this->enabled ) return false; // if it's enabled, do not allow ownership to be released, even with no pins 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), token, 0); diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp index 5966873a..bd3584d4 100644 --- a/libraries/Servo/src/nrf52/Servo.cpp +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -108,7 +108,10 @@ void Servo::detach() HardwarePWM * pwm = this->pwm; this->pwm = nullptr; pwm->removePin(pin); - pwm->releaseOwnership(_servoToken); // ignore failure ... which happens if a pin is still in use, for example + if (pwm->usedChannelCount() == 0) { + pwm->stop(); // disables peripheral so can release ownership + pwm->releaseOwnership(_servoToken); + } } void Servo::write(int value) From c190318bb9af4d342333c22fb708065effd63e2b Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 3 May 2020 20:23:13 -0700 Subject: [PATCH 11/76] Use const void* for ownership token --- cores/nRF5/HardwarePWM.cpp | 8 ++++---- cores/nRF5/HardwarePWM.h | 9 +++++---- cores/nRF5/Tone.cpp | 2 +- cores/nRF5/wiring_analog.cpp | 10 +++++----- libraries/Servo/src/nrf52/Servo.cpp | 2 +- 5 files changed, 16 insertions(+), 15 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index fc8ceb00..85db2961 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -54,21 +54,21 @@ HardwarePWM* HwPWMx[] = }; // 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(void const * 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 - if (this->enabled ) return false; // if it's enabled, do not allow new ownership, even with no pins in use + if (this->enabled() ) return false; // if it's enabled, do not allow new ownership, even with no pins 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) +bool HardwarePWM::releaseOwnership(void const * 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 - if ( this->enabled ) return false; // if it's enabled, do not allow ownership to be released, even with no pins in use + if ( this->enabled() ) return false; // if it's enabled, do not allow ownership to be released, even with no pins 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), token, 0); diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index 5bfe6977..59751466 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -50,7 +50,7 @@ class HardwarePWM private: enum { MAX_CHANNELS = 4 }; // Max channel per group NRF_PWM_Type* _pwm; - uintptr_t _owner_token = 0; + void const * _owner_token = nullptr; uint16_t _seq0[MAX_CHANNELS]; @@ -71,11 +71,12 @@ 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 (void const * 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(void const * token); + // allows caller to verify that they own the peripheral - __INLINE bool isOwner(uintptr_t token) __attribute__((__always_inline__)) + __INLINE bool isOwner(void const * token) __attribute__((__always_inline__)) { return this->_owner_token == token; } diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 20def523..5f073d4e 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -41,7 +41,7 @@ Version Modified By Date Comments unsigned long int count_duration=0; volatile bool no_stop = false; uint8_t pin_sound=0; -static uintptr_t _toneToken = (uintptr_t)(&_toneToken); +static char const * _toneToken = "Tone"; void tone(uint8_t pin, unsigned int frequency, unsigned long duration) diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index e7d7b2f4..79ccf408 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -47,7 +47,7 @@ extern "C" { static uint8_t _lastAnalogWriteResolution; -static const uintptr_t _token = (uintptr_t)(&_lastAnalogWriteResolution); +static char const * _analogToken = "analog"; /** * This will apply to all PWM Hardware currently used by analogWrite(), @@ -59,7 +59,7 @@ void analogWriteResolution( uint8_t res ) _lastAnalogWriteResolution = res; for (int i = 0; iisOwner(_token)) continue; + if (!HwPWMx[i]->isOwner(_analogToken)) continue; HwPWMx[i]->setResolution(res); } } @@ -80,7 +80,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(_token)) { + if (!HwPWMx[i]->isOwner(_analogToken)) { LOG_LV3("ANA", "not currently owner of PWM %d", i); continue; // skip if not owner of this PWM instance } @@ -98,7 +98,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(_token)) { + if (!HwPWMx[i]->isOwner(_analogToken)) { LOG_LV3("ANA", "not currently owner of PWM %d", i); continue; } @@ -118,7 +118,7 @@ void analogWrite( uint32_t pin, uint32_t value ) // 2. it currently has no pins in use. for(int i=0; itakeOwnership(_token)) { + if (!HwPWMx[i]->takeOwnership(_analogToken)) { LOG_LV3("ANA", "Could not take ownership of PWM %d", i); continue; } diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp index bd3584d4..adbcf455 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 = (uintptr_t)(&_servoToken); +static char const * _servoToken = "Servo"; static servo_t servos[MAX_SERVOS]; // static array of servo structures uint8_t ServoCount = 0; // the total number of attached servos From 027bcd348cde77859f7241d21d0e14a88e532a1c Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 3 May 2020 23:46:34 -0700 Subject: [PATCH 12/76] Fix check for connected pins --- cores/nRF5/HardwarePWM.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 85db2961..cd070aa3 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -244,7 +244,7 @@ uint8_t HardwarePWM::usedChannelCount(void) uint8_t usedChannels = 0; for(int i=0; iPSEL.OUT[i] & PWM_PSEL_OUT_CONNECT_Msk ) + if ( (_pwm->PSEL.OUT[i] & PWM_PSEL_OUT_CONNECT_Msk) != (PWM_PSEL_OUT_CONNECT_Disconnected << PWM_PSEL_OUT_CONNECT_Pos) ) { usedChannels++; } From 85e41afe270ccd1c6dcba3995402ca527a75fe5e Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 10 May 2020 00:02:06 -0700 Subject: [PATCH 13/76] remove dead code --- cores/nRF5/Tone.cpp | 70 --------------------------------------------- 1 file changed, 70 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 5f073d4e..30b6eacf 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -78,11 +78,6 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) no_stop = true; } - // PWM configuration depends on the following: - // [ ] time_per - // [ ] duty ( via seq ) - // [ ] pin ( via pins[0] ) - // Configure PWM static uint16_t seq_values[]={0}; //In each value, the most significant bit (15) determines the polarity of the output @@ -95,35 +90,12 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) 0 }; -#if 0 - //assign pin to pwm channel - look at WVariant.h for details about ulPWMChannel attribute - uint8_t pwm_type=g_APinDescription[pin].ulPWMChannel; - if(pwm_type == NOT_ON_PWM) - return; - - uint32_t pins[NRF_PWM_CHANNEL_COUNT]={NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}; - pins[pwm_type & 0x0F]=g_APinDescription[pin].ulPin; - IRQn_Type IntNo = PWM0_IRQn; - NRF_PWM_Type * PWMInstance = NRF_PWM0; - switch(pwm_type &0xF0){ - case 16://0x10 - PWMInstance = NRF_PWM1; - IntNo = PWM1_IRQn; - break; - case 32://0x20 - PWMInstance = NRF_PWM2; - IntNo = PWM2_IRQn; - break; - } -#else - // Use fixed PWM2, TODO could conflict with other usage uint32_t pins[NRF_PWM_CHANNEL_COUNT]={NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}; pins[0] = g_ADigitalPinMap[pin]; IRQn_Type IntNo = PWM2_IRQn; NRF_PWM_Type * PWMInstance = NRF_PWM2; -#endif nrf_pwm_pins_set(PWMInstance, pins); nrf_pwm_enable(PWMInstance); @@ -150,21 +122,7 @@ void noTone(uint8_t pin) return; } -#if 0 - uint8_t pwm_type=g_APinDescription[pin].ulPWMChannel; - NRF_PWM_Type * PWMInstance = NRF_PWM0; - switch(pwm_type &0xF0){ - case 16://0x10 - PWMInstance = NRF_PWM1; - break; - case 32://0x20 - PWMInstance = NRF_PWM2; - break; - } -#else NRF_PWM_Type * PWMInstance = NRF_PWM2; -#endif - nrf_pwm_task_trigger(PWMInstance, NRF_PWM_TASK_STOP); nrf_pwm_disable(PWMInstance); } @@ -173,34 +131,6 @@ void noTone(uint8_t pin) extern "C"{ #endif -#if 0 -void PWM0_IRQHandler(void){ - nrf_pwm_event_clear(NRF_PWM0, NRF_PWM_EVENT_PWMPERIODEND); - if(!no_stop){ - count_duration--; - if(count_duration == 0) - noTone(pin_sound); - else - nrf_pwm_task_trigger(NRF_PWM0, NRF_PWM_TASK_SEQSTART0); - } - else - nrf_pwm_task_trigger(NRF_PWM0, NRF_PWM_TASK_SEQSTART0); -} - -void PWM1_IRQHandler(void){ - nrf_pwm_event_clear(NRF_PWM1, NRF_PWM_EVENT_PWMPERIODEND); - if(!no_stop){ - count_duration--; - if(count_duration == 0) - noTone(pin_sound); - else - nrf_pwm_task_trigger(NRF_PWM1, NRF_PWM_TASK_SEQSTART0); - } - else - nrf_pwm_task_trigger(NRF_PWM1, NRF_PWM_TASK_SEQSTART0); -} -#endif - void PWM2_IRQHandler(void){ nrf_pwm_event_clear(NRF_PWM2, NRF_PWM_EVENT_PWMPERIODEND); if(!no_stop){ From a6e0d2c925691ab5f588702455b952e2161410e4 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 10 May 2020 18:14:10 -0700 Subject: [PATCH 14/76] Prefer `uintptr_t` to `void const *` for ownership token --- cores/nRF5/HardwarePWM.cpp | 61 ++++++++++++++++++++++++++++++++------ cores/nRF5/HardwarePWM.h | 32 +++++++++++++------- 2 files changed, 73 insertions(+), 20 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index cd070aa3..6c354fb0 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -53,9 +53,51 @@ HardwarePWM* HwPWMx[] = #endif }; -// returns true ONLY when (1) no PWM channel has a pin, and (2) the owner token is nullptr -bool HardwarePWM::takeOwnership(void const * token) +bool can_stringify_token(uintptr_t token) { + uint8_t * t = (uint8_t *)&token; + for (size_t i = 0; i < sizeof(uintptr_t); ++i, ++t) + { + uint8_t x = *t; + if ((x < 0x20) || (x > 0x7E)) return false; + } + return true; +} + +void HardwarePWM::DebugOutput(Stream& logger) +{ + const size_t count = arrcount(HwPWMx); + logger.printf("HwPWM Debug:"); + for (size_t i = 0; i < count; i++) { + HardwarePWM const * pwm = HwPWMx[i]; + uintptr_t token = pwm->_owner_token; + 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++) { + uint32_t r = pwm->_pwm->PSEL.OUT[i]; // only read it once + if ( (r & PWM_PSEL_OUT_CONNECT_Msk) != (PWM_PSEL_OUT_CONNECT_Disconnected << PWM_PSEL_OUT_CONNECT_Pos) ) { + logger.printf(" %02x", r & 0x1F); + } else { + logger.printf(" xx"); + } + } + } + logger.printf("\n"); +} + + + +// 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) return false; // cannot take ownership with nullptr 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 if (this->enabled() ) return false; // if it's enabled, do not allow new ownership, even with no pins in use @@ -64,8 +106,9 @@ bool HardwarePWM::takeOwnership(void const * token) 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(void const * token) +bool HardwarePWM::releaseOwnership(uintptr_t token) { + if (token == 0) return false; // cannot release ownership with nullptr 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 if ( this->enabled() ) return false; // if it's enabled, do not allow ownership to be released, even with no pins in use @@ -74,9 +117,9 @@ bool HardwarePWM::releaseOwnership(void const * token) return __sync_bool_compare_and_swap(&(this->_owner_token), token, 0); } -HardwarePWM::HardwarePWM(NRF_PWM_Type* pwm) +HardwarePWM::HardwarePWM(NRF_PWM_Type* pwm) : + _pwm(pwm) { - _pwm = pwm; arrclr(_seq0); _max_value = 255; @@ -225,7 +268,7 @@ bool HardwarePWM::writePin(uint8_t pin, uint16_t value, bool inverted) return writeChannel(ch, value, inverted); } -uint16_t HardwarePWM::readPin(uint8_t pin) +uint16_t HardwarePWM::readPin(uint8_t pin) const { int ch = pin2channel(pin); VERIFY( ch >= 0, 0); @@ -233,13 +276,13 @@ uint16_t HardwarePWM::readPin(uint8_t pin) return readChannel(ch); } -uint16_t HardwarePWM::readChannel(uint8_t ch) +uint16_t HardwarePWM::readChannel(uint8_t ch) const { // remove inverted bit return (_seq0[ch] & 0x7FFF); } -uint8_t HardwarePWM::usedChannelCount(void) +uint8_t HardwarePWM::usedChannelCount(void) const { uint8_t usedChannels = 0; for(int i=0; i_owner_token == token; } + __INLINE bool takeOwnership (void const * token) + { return takeOwnership((uintptr_t)token); } + __INLINE bool releaseOwnership(void const * token) + { return releaseOwnership((uintptr_t)token); } + __INLINE bool isOwner (void const * token) const + __attribute__ ((__always_inline__)) + { return isOwner((uintptr_t)token); } bool addPin (uint8_t pin); bool removePin (uint8_t pin); - int pin2channel(uint8_t pin) + int pin2channel(uint8_t pin) const { pin = g_ADigitalPinMap[pin]; for(int i=0; i= 0; } @@ -108,12 +115,15 @@ class HardwarePWM bool writeChannel(uint8_t ch , uint16_t value, bool inverted = false); // Read current set value - uint16_t readPin (uint8_t pin); - uint16_t readChannel (uint8_t ch); + uint16_t readPin (uint8_t pin) const; + uint16_t readChannel (uint8_t ch) const; // Get count of used / free channels - uint8_t usedChannelCount(); - uint8_t freeChannelCount(); + uint8_t usedChannelCount() const; + uint8_t freeChannelCount() const; + + // for debug/validation + static void DebugOutput(Stream& logger); }; extern HardwarePWM HwPWM0; From 0acacf67b813c7689ccb2113d88e5f806518d57e Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 10 May 2020 18:52:54 -0700 Subject: [PATCH 15/76] Finish conversion back to `uintptr_t` token --- cores/nRF5/HardwarePWM.cpp | 4 ++-- cores/nRF5/HardwarePWM.h | 13 ++++--------- cores/nRF5/Tone.cpp | 3 +-- cores/nRF5/wiring_analog.cpp | 2 +- libraries/Servo/src/nrf52/Servo.cpp | 2 +- 5 files changed, 9 insertions(+), 15 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 6c354fb0..bf68dcb7 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -53,6 +53,7 @@ HardwarePWM* HwPWMx[] = #endif }; +#if CFG_DEBUG bool can_stringify_token(uintptr_t token) { uint8_t * t = (uint8_t *)&token; @@ -91,8 +92,7 @@ void HardwarePWM::DebugOutput(Stream& logger) } logger.printf("\n"); } - - +#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) diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index 7457d164..fbf9a672 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -76,17 +76,11 @@ class HardwarePWM bool releaseOwnership(uintptr_t token); // allows caller to verify that they own the peripheral - __INLINE bool isOwner(uintptr_t token) const __attribute__((__always_inline__)) + __INLINE bool isOwner(uintptr_t token) const + __attribute__ ((__always_inline__)) { return this->_owner_token == token; } - __INLINE bool takeOwnership (void const * token) - { return takeOwnership((uintptr_t)token); } - __INLINE bool releaseOwnership(void const * token) - { return releaseOwnership((uintptr_t)token); } - __INLINE bool isOwner (void const * token) const - __attribute__ ((__always_inline__)) - { return isOwner((uintptr_t)token); } bool addPin (uint8_t pin); bool removePin (uint8_t pin); @@ -122,8 +116,9 @@ class HardwarePWM uint8_t usedChannelCount() const; uint8_t freeChannelCount() const; - // for debug/validation +#if CFG_DEBUG static void DebugOutput(Stream& logger); +#endif // CFG_DEBUG }; extern HardwarePWM HwPWM0; diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 30b6eacf..ed70680e 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -41,8 +41,7 @@ Version Modified By Date Comments unsigned long int count_duration=0; volatile bool no_stop = false; uint8_t pin_sound=0; -static char const * _toneToken = "Tone"; - +static uintptr_t _toneToken = 0x656e6f54; // 'T' 'o' 'n' 'e' void tone(uint8_t pin, unsigned int frequency, unsigned long duration) { diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 79ccf408..3d2aadb7 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -47,7 +47,7 @@ extern "C" { static uint8_t _lastAnalogWriteResolution; -static char const * _analogToken = "analog"; +static uintptr_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 adbcf455..0d4f6b16 100644 --- a/libraries/Servo/src/nrf52/Servo.cpp +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -21,7 +21,7 @@ #include #include -static char const * _servoToken = "Servo"; +static uintptr_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 145167b579532f50035bde115517a9138d8b66f6 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Wed, 13 May 2020 10:35:05 -0700 Subject: [PATCH 16/76] tone() auto-release ownership --- cores/nRF5/HardwarePWM.cpp | 11 ++++- cores/nRF5/HardwarePWM.h | 4 +- cores/nRF5/Tone.cpp | 82 ++++++++++++++++++++++++-------------- 3 files changed, 64 insertions(+), 33 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index bf68dcb7..0e2b88d4 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -65,6 +65,7 @@ bool can_stringify_token(uintptr_t token) return true; } + void HardwarePWM::DebugOutput(Stream& logger) { const size_t count = arrcount(HwPWMx); @@ -79,7 +80,7 @@ void HardwarePWM::DebugOutput(Stream& logger) 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); + logger.printf(" %08x", token); } for (size_t j = 0; j < MAX_CHANNELS; j++) { uint32_t r = pwm->_pwm->PSEL.OUT[i]; // only read it once @@ -108,6 +109,14 @@ bool HardwarePWM::takeOwnership(uintptr_t 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 (!releaseOwnershipFromISR(token)) { + LOG_LV1("HwPWM", "Failed to release ownership of PWM %p using token %x", _pwm, token); + return false; + } + return true; +} +bool HardwarePWM::releaseOwnershipFromISR(uintptr_t token) { + // Do not do any logging if called from ISR ... if (token == 0) return false; // cannot release ownership with nullptr 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 diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index fbf9a672..e4c9ecf1 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -50,7 +50,7 @@ class HardwarePWM private: enum { MAX_CHANNELS = 4 }; // Max channel per group NRF_PWM_Type * const _pwm; - uintptr_t _owner_token = 0; + volatile uintptr_t _owner_token = 0; uint16_t _seq0[MAX_CHANNELS]; @@ -74,6 +74,8 @@ class HardwarePWM 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); + // As above, but ensured safe to call from ISR + bool releaseOwnershipFromISR(uintptr_t token); // allows caller to verify that they own the peripheral __INLINE bool isOwner(uintptr_t token) const diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index ed70680e..69026798 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -38,15 +38,23 @@ Version Modified By Date Comments #include "Tone.h" #include "WVariant.h" -unsigned long int count_duration=0; +volatile unsigned long int count_duration=0; volatile bool no_stop = false; uint8_t pin_sound=0; static uintptr_t _toneToken = 0x656e6f54; // 'T' 'o' 'n' 'e' +// NOTE: Currently hard-coded to only use PWM2 ... +// These are the relvant hard-coded variables +// (plus the ISR PWM2_IRQHandler) +static IRQn_Type const _IntNo = PWM2_IRQn; +static NRF_PWM_Type * const _PWMInstance = NRF_PWM2; +static HardwarePWM * const _HwPWM = HwPWMx[2]; + void tone(uint8_t pin, unsigned int frequency, unsigned long duration) { static_assert(sizeof(unsigned long) == sizeof(uint32_t)); - + bool new_no_stop; + unsigned long int new_count_duration = (unsigned long int)-1L; unsigned int time_per=0; // limit frequency to reasonable audible range @@ -55,9 +63,15 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) return; } + // set nostop to true to avoid race condition. + // Specifically, race between a tone finishing + // after checking for ownership (which releases ownership) + // No effect if a tone is not playing.... + no_stop = true; + // Use fixed PWM2 (due to need to connect interrupt) - if (!HwPWMx[2]->isOwner(_toneToken) && - !HwPWMx[2]->takeOwnership(_toneToken)) { + if (!_HwPWM->isOwner(_toneToken) && + !_HwPWM->takeOwnership(_toneToken)) { LOG_LV1("TON", "unable to allocate PWM2 to Tone"); return; } @@ -66,15 +80,15 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) time_per=per/0.000008; unsigned int duty=time_per/2; if(duration > 0) { - no_stop = false; + new_no_stop = false; float mil=float(duration)/1000; if(per>mil) { - count_duration=1; + new_count_duration = 1; } else { - count_duration= mil/per; + new_count_duration = mil/per; } } else { - no_stop = true; + new_no_stop = true; } // Configure PWM @@ -88,42 +102,45 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) 0, 0 }; - - // Use fixed PWM2, TODO could conflict with other usage + uint32_t pins[NRF_PWM_CHANNEL_COUNT]={NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}; pins[0] = g_ADigitalPinMap[pin]; - IRQn_Type IntNo = PWM2_IRQn; - NRF_PWM_Type * PWMInstance = NRF_PWM2; - - nrf_pwm_pins_set(PWMInstance, pins); - nrf_pwm_enable(PWMInstance); - nrf_pwm_configure(PWMInstance, NRF_PWM_CLK_125kHz, NRF_PWM_MODE_UP, time_per); - nrf_pwm_decoder_set(PWMInstance, NRF_PWM_LOAD_COMMON, NRF_PWM_STEP_AUTO); - nrf_pwm_sequence_set(PWMInstance, 0, &seq); - nrf_pwm_shorts_enable(PWMInstance, NRF_PWM_SHORT_SEQEND0_STOP_MASK); // shortcut for when SEQ0 ends, PWM output will automatically stop - // enable interrupt - nrf_pwm_event_clear(PWMInstance, NRF_PWM_EVENT_PWMPERIODEND); - nrf_pwm_int_enable(PWMInstance, NRF_PWM_INT_PWMPERIODEND_MASK); - NVIC_SetPriority(IntNo, 6); //low priority - NVIC_ClearPendingIRQ(IntNo); - NVIC_EnableIRQ(IntNo); + count_duration = 0x6FFF; // large enough to avoid hitting zero in next few lines + no_stop = new_no_stop; - nrf_pwm_task_trigger(PWMInstance, NRF_PWM_TASK_SEQSTART0); + nrf_pwm_pins_set(_PWMInstance, pins); + nrf_pwm_enable(_PWMInstance); + nrf_pwm_configure(_PWMInstance, NRF_PWM_CLK_125kHz, NRF_PWM_MODE_UP, time_per); + nrf_pwm_decoder_set(_PWMInstance, NRF_PWM_LOAD_COMMON, NRF_PWM_STEP_AUTO); + nrf_pwm_sequence_set(_PWMInstance, 0, &seq); + nrf_pwm_shorts_enable(_PWMInstance, NRF_PWM_SHORT_SEQEND0_STOP_MASK); // shortcut for when SEQ0 ends, PWM output will automatically stop + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_PWMPERIODEND); + nrf_pwm_int_enable(_PWMInstance, NRF_PWM_INT_PWMPERIODEND_MASK); + NVIC_SetPriority(_IntNo, 6); //low priority + NVIC_ClearPendingIRQ(_IntNo); + NVIC_EnableIRQ(_IntNo); + count_duration = new_count_duration; + nrf_pwm_task_trigger(_PWMInstance, NRF_PWM_TASK_SEQSTART0); } void noTone(uint8_t pin) { - if (!HwPWMx[2]->isOwner(_toneToken)) { + if (!_HwPWM->isOwner(_toneToken)) { LOG_LV1("TON", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); return; } - - NRF_PWM_Type * PWMInstance = NRF_PWM2; - nrf_pwm_task_trigger(PWMInstance, NRF_PWM_TASK_STOP); - nrf_pwm_disable(PWMInstance); + nrf_pwm_task_trigger(_PWMInstance, NRF_PWM_TASK_STOP); + nrf_pwm_disable(_PWMInstance); + _PWMInstance->PSEL.OUT[0] = NRF_PWM_PIN_NOT_CONNECTED; + NVIC_DisableIRQ(_IntNo); + _HwPWM->releaseOwnership(_toneToken); + if (_HwPWM->isOwner(_toneToken)) { + LOG_LV1("TON", "stopped tone, but failed to release ownership of PWM peripheral?"); + return; + } } #ifdef __cplusplus @@ -137,6 +154,9 @@ void PWM2_IRQHandler(void){ if(count_duration == 0) { nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_STOP); nrf_pwm_disable(NRF_PWM2); + _PWMInstance->PSEL.OUT[0] = NRF_PWM_PIN_NOT_CONNECTED; + NVIC_DisableIRQ(PWM2_IRQn); + _HwPWM->releaseOwnershipFromISR(_toneToken); } else { nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_SEQSTART0); } From bbc453156eac9e010127f68562ce75824de7e650 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Wed, 13 May 2020 17:22:47 -0700 Subject: [PATCH 17/76] Improve logging for end users --- cores/nRF5/HardwarePWM.cpp | 54 ++++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 0e2b88d4..84a43c05 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -65,7 +65,6 @@ bool can_stringify_token(uintptr_t token) return true; } - void HardwarePWM::DebugOutput(Stream& logger) { const size_t count = arrcount(HwPWMx); @@ -98,10 +97,28 @@ void HardwarePWM::DebugOutput(Stream& logger) // 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) return false; // cannot take ownership with nullptr - 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 - if (this->enabled() ) return false; // if it's enabled, do not allow new ownership, even with no pins in use + if (token == 0) { + 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) { + LOG_LV1("HwPWM", "failing to acquire ownership because already owned by requesting token (cannot take ownership twice)"); + } + if (this->_owner_token != 0) { + LOG_LV3("HwPWM", "failing to acquire ownership because already owned by other token"); + return false; + } + if (this->usedChannelCount() != 0) { + LOG_LV3("HwPWM", "failing to acquire ownership because at least one channel connected"); + return false; + } + if (this->enabled()) { + LOG_LV3("HwPWM", "failing to acquire ownership because peripheral is already enabled"); + return false; + } + // TODO: warn, but do not fail, if taking ownership with IRQs already enabled + // NVIC_GetActive + // 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); @@ -109,11 +126,32 @@ bool HardwarePWM::takeOwnership(uintptr_t 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 (!releaseOwnershipFromISR(token)) { - LOG_LV1("HwPWM", "Failed to release ownership of PWM %p using token %x", _pwm, token); + if (token == 0) { + LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in releaseOwnership)"); return false; } - return true; + 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 + } + // TODO: warn, but do not fail, if releasing ownership with IRQs enabled + // NVIC_GetActive + + // use gcc built-in intrinsic to ensure atomicity + // See https://gcc.gnu.org/onlinedocs/gcc/_005f_005fsync-Builtins.html + bool result = __sync_bool_compare_and_swap(&(this->_owner_token), token, 0); + if (!result) { + LOG_LV1("HwPWM", "race condition resulted in failure to acquire ownership"); + } + return result; } bool HardwarePWM::releaseOwnershipFromISR(uintptr_t token) { // Do not do any logging if called from ISR ... From aebdca3f639f6978f423e890da9d5169e718cae0 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Wed, 13 May 2020 22:41:16 -0700 Subject: [PATCH 18/76] Ensure default value for `analogWriteResolution()` --- cores/nRF5/wiring_analog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 3d2aadb7..b2e88115 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -46,7 +46,7 @@ extern "C" { -static uint8_t _lastAnalogWriteResolution; +static uint8_t _lastAnalogWriteResolution = 8; // default is 256 levels static uintptr_t _analogToken = 0x676f6c41; // 'A' 'l' 'o' 'g' /** From dd06e2f05a9332ef9b799511e0c395702cd5e769 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Thu, 14 May 2020 00:58:59 -0700 Subject: [PATCH 19/76] Fix HwPWM debug logging typo --- cores/nRF5/HardwarePWM.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 84a43c05..fbc2ec73 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -82,7 +82,7 @@ void HardwarePWM::DebugOutput(Stream& logger) logger.printf(" %08x", token); } for (size_t j = 0; j < MAX_CHANNELS; j++) { - uint32_t r = pwm->_pwm->PSEL.OUT[i]; // only read it once + uint32_t r = pwm->_pwm->PSEL.OUT[j]; // only read it once if ( (r & PWM_PSEL_OUT_CONNECT_Msk) != (PWM_PSEL_OUT_CONNECT_Disconnected << PWM_PSEL_OUT_CONNECT_Pos) ) { logger.printf(" %02x", r & 0x1F); } else { From be9927e497830f2e419839b9454bcf6971b565c0 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Fri, 10 Jul 2020 17:34:20 -0700 Subject: [PATCH 20/76] Simplify by auto-detecting when called from ISR Thanks to @hathach for recommendation: https://github.com/adafruit/Adafruit_nRF52_Arduino/pull/496#discussion_r452712103 --- cores/nRF5/HardwarePWM.cpp | 48 +++++++++++++++++++++++--------------- cores/nRF5/HardwarePWM.h | 2 -- cores/nRF5/Tone.cpp | 2 +- 3 files changed, 30 insertions(+), 22 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index fbc2ec73..30622044 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -97,23 +97,34 @@ void HardwarePWM::DebugOutput(Stream& logger) // 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) { - LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in takeOwnership)"); + 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) { - LOG_LV1("HwPWM", "failing to acquire ownership because already owned by requesting token (cannot take ownership twice)"); + if (notInIsr) { + LOG_LV1("HwPWM", "failing to acquire ownership because already owned by requesting token (cannot take ownership twice)"); + } } if (this->_owner_token != 0) { - LOG_LV3("HwPWM", "failing to acquire ownership because already owned by other token"); + if (notInIsr) { + LOG_LV3("HwPWM", "failing to acquire ownership because already owned by other token"); + } return false; } if (this->usedChannelCount() != 0) { - LOG_LV3("HwPWM", "failing to acquire ownership because at least one channel connected"); + if (notInIsr) { + LOG_LV3("HwPWM", "failing to acquire ownership because at least one channel connected"); + } return false; } if (this->enabled()) { - LOG_LV3("HwPWM", "failing to acquire ownership because peripheral is already enabled"); + if (notInIsr) { + LOG_LV3("HwPWM", "failing to acquire ownership because peripheral is already enabled"); + } return false; } // TODO: warn, but do not fail, if taking ownership with IRQs already enabled @@ -126,20 +137,29 @@ bool HardwarePWM::takeOwnership(uintptr_t 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) { - LOG_LV1("HwPWM", "zero / nullptr is not a valid ownership token (attempted use in releaseOwnership)"); + if (notInIsr) { + 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"); + if (notInIsr) { + 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 (notInIsr) { + 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 (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 @@ -153,16 +173,6 @@ bool HardwarePWM::releaseOwnership(uintptr_t token) } return result; } -bool HardwarePWM::releaseOwnershipFromISR(uintptr_t token) { - // Do not do any logging if called from ISR ... - if (token == 0) return false; // cannot release ownership with nullptr - 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 - if ( this->enabled() ) return false; // if it's enabled, do not allow ownership to be released, even with no pins 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), token, 0); -} HardwarePWM::HardwarePWM(NRF_PWM_Type* pwm) : _pwm(pwm) diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index e4c9ecf1..d3bda233 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -74,8 +74,6 @@ class HardwarePWM 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); - // As above, but ensured safe to call from ISR - bool releaseOwnershipFromISR(uintptr_t token); // allows caller to verify that they own the peripheral __INLINE bool isOwner(uintptr_t token) const diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 69026798..15fb03b0 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -156,7 +156,7 @@ void PWM2_IRQHandler(void){ nrf_pwm_disable(NRF_PWM2); _PWMInstance->PSEL.OUT[0] = NRF_PWM_PIN_NOT_CONNECTED; NVIC_DisableIRQ(PWM2_IRQn); - _HwPWM->releaseOwnershipFromISR(_toneToken); + _HwPWM->releaseOwnership(_toneToken); } else { nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_SEQSTART0); } From 37935c7938288dd97f6dd781be0a9d258ddd8740 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Fri, 10 Jul 2020 19:31:58 -0700 Subject: [PATCH 21/76] Remove always_inline attribute Per @hathach request https://github.com/adafruit/Adafruit_nRF52_Arduino/pull/496#discussion_r452713305 --- cores/nRF5/HardwarePWM.h | 1 - 1 file changed, 1 deletion(-) diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index d3bda233..25e60e93 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -77,7 +77,6 @@ class HardwarePWM // allows caller to verify that they own the peripheral __INLINE bool isOwner(uintptr_t token) const - __attribute__ ((__always_inline__)) { return this->_owner_token == token; } From e58b39e2ded01799764d5c1ad86dc43577b4db10 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Fri, 10 Jul 2020 19:53:48 -0700 Subject: [PATCH 22/76] Reduce debug output for analog_write() Remove all output when the pin is already configured and everything works. --- cores/nRF5/wiring_analog.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index b2e88115..22ece424 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -81,16 +81,13 @@ void analogWrite( uint32_t pin, uint32_t value ) for(int i=0; iisOwner(_analogToken)) { - LOG_LV3("ANA", "not currently owner of PWM %d", i); continue; // skip if not owner of this PWM instance } int const ch = HwPWMx[i]->pin2channel(pin); if (ch < 0) { - LOG_LV3("ANA", "pin %d is not used by PWM %d", pin, i); continue; // pin not in use by this PWM instance } - LOG_LV2("ANA", "updating pin %" PRIu32 " used by PWM %d", pin, i); HwPWMx[i]->writeChannel(ch, value); return; } From eb55315d4fad7775f614c3e0d2610e526462ca2c Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Fri, 10 Jul 2020 20:49:14 -0700 Subject: [PATCH 23/76] Explicit `void` for no parameters Per @hathach comments https://github.com/adafruit/Adafruit_nRF52_Arduino/pull/496/files/d7e005cc99d4db22a3e6940279e5a59b995f247e#r452772810 --- cores/nRF5/HardwarePWM.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index 25e60e93..46bcd334 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -112,8 +112,8 @@ class HardwarePWM uint16_t readChannel (uint8_t ch) const; // Get count of used / free channels - uint8_t usedChannelCount() const; - uint8_t freeChannelCount() const; + uint8_t usedChannelCount(void) const; + uint8_t freeChannelCount(void) const; #if CFG_DEBUG static void DebugOutput(Stream& logger); From a2a43719c583f7fb2d6dfa38ad10274e6537a388 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Fri, 10 Jul 2020 20:53:59 -0700 Subject: [PATCH 24/76] Remove static assertion Per @hathach request https://github.com/adafruit/Adafruit_nRF52_Arduino/pull/496/files/d7e005cc99d4db22a3e6940279e5a59b995f247e?file-filters%5B%5D=.c&file-filters%5B%5D=.cpp#r452765910 --- cores/nRF5/Tone.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 15fb03b0..57af183e 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -52,7 +52,6 @@ static HardwarePWM * const _HwPWM = HwPWMx[2]; void tone(uint8_t pin, unsigned int frequency, unsigned long duration) { - static_assert(sizeof(unsigned long) == sizeof(uint32_t)); bool new_no_stop; unsigned long int new_count_duration = (unsigned long int)-1L; unsigned int time_per=0; From 43da1739a37346fc4f9b8395345f987542ade2f2 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Fri, 10 Jul 2020 21:23:14 -0700 Subject: [PATCH 25/76] Update noTone() to be safe to call from ISR --- cores/nRF5/Tone.cpp | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 57af183e..9cdf312b 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -127,8 +127,12 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) void noTone(uint8_t pin) { + bool notInIsr = !isInISR(); + if (!_HwPWM->isOwner(_toneToken)) { - LOG_LV1("TON", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); + if (notInIsr) { + LOG_LV1("TON", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); + } return; } nrf_pwm_task_trigger(_PWMInstance, NRF_PWM_TASK_STOP); @@ -137,7 +141,9 @@ void noTone(uint8_t pin) NVIC_DisableIRQ(_IntNo); _HwPWM->releaseOwnership(_toneToken); if (_HwPWM->isOwner(_toneToken)) { - LOG_LV1("TON", "stopped tone, but failed to release ownership of PWM peripheral?"); + if (notInIsr) { + LOG_LV1("TON", "stopped tone, but failed to release ownership of PWM peripheral?"); + } return; } } @@ -151,11 +157,8 @@ void PWM2_IRQHandler(void){ if(!no_stop){ count_duration--; if(count_duration == 0) { - nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_STOP); - nrf_pwm_disable(NRF_PWM2); - _PWMInstance->PSEL.OUT[0] = NRF_PWM_PIN_NOT_CONNECTED; - NVIC_DisableIRQ(PWM2_IRQn); - _HwPWM->releaseOwnership(_toneToken); + uint8_t pin = _PWMInstance->PSEL.OUT[0]; + noTone(pin); } else { nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_SEQSTART0); } From d00de2d783d9b2ccc0cadc7e37381e3ee2c5c857 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Fri, 10 Jul 2020 21:27:42 -0700 Subject: [PATCH 26/76] Change variable name per @hathach request. --- cores/nRF5/wiring_analog.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 22ece424..5267a64c 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -46,7 +46,7 @@ extern "C" { -static uint8_t _lastAnalogWriteResolution = 8; // default is 256 levels +static uint8_t _analogResolution = 8; // default is 256 levels static uintptr_t _analogToken = 0x676f6c41; // 'A' 'l' 'o' 'g' /** @@ -56,7 +56,7 @@ static uintptr_t _analogToken = 0x676f6c41; // 'A' 'l' 'o' 'g' void analogWriteResolution( uint8_t res ) { // save the resolution for when adding a new instance - _lastAnalogWriteResolution = res; + _analogResolution = res; for (int i = 0; iisOwner(_analogToken)) continue; @@ -121,7 +121,7 @@ void analogWrite( uint32_t pin, uint32_t value ) } // apply the cached analog resolution to newly owned instances - HwPWMx[i]->setResolution(_lastAnalogWriteResolution); + 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); From d7b18ed40f4104465d413da7ad42a5b1a39a95b7 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Fri, 10 Jul 2020 21:41:27 -0700 Subject: [PATCH 27/76] Code review required comment removal --- libraries/Servo/src/nrf52/Servo.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp index 0d4f6b16..02995550 100644 --- a/libraries/Servo/src/nrf52/Servo.cpp +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -129,7 +129,7 @@ void Servo::write(int value) void Servo::writeMicroseconds(int value) { - if (this->pwm) { // pwm is only set when this->servoIndex != INVALID_SERVO + if (this->pwm) { uint8_t pin = servos[this->servoIndex].Pin.nbr; this->pwm->writePin(pin, value/DUTY_CYCLE_RESOLUTION); } @@ -142,7 +142,7 @@ int Servo::read() // return the value as degrees int Servo::readMicroseconds() { - if (this->pwm) { // pwm is only set when this->servoIndex != INVALID_SERVO + if (this->pwm) { uint8_t pin = servos[this->servoIndex].Pin.nbr; return this->pwm->readPin(pin)*DUTY_CYCLE_RESOLUTION; } From 5bb5b132e589318922daed66ffa6b98adaf3ca63 Mon Sep 17 00:00:00 2001 From: hathach Date: Sat, 1 Aug 2020 21:47:38 +0700 Subject: [PATCH 28/76] fix power usbready not handled if bluefruit begin() is called fast enough --- cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp | 21 ++++--- cores/nRF5/TinyUSB/tusb_config.h | 4 ++ cores/nRF5/freertos/config/FreeRTOSConfig.h | 3 +- cores/nRF5/main.cpp | 7 +++ libraries/Bluefruit52Lib/src/bluefruit.cpp | 63 ++++++++++++--------- 5 files changed, 58 insertions(+), 40 deletions(-) diff --git a/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp b/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp index e4f50237..a66ba1d7 100644 --- a/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp +++ b/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp @@ -63,6 +63,14 @@ extern "C" void USBD_IRQHandler(void) // Init usb hardware when starting up. Softdevice is not enabled yet static void usb_hardware_init(void) { + // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice + // 2 is highest for application + NVIC_SetPriority(USBD_IRQn, 2); + + // USB power may already be ready at this time -> no event generated + // We need to invoke the handler based on the status initially + uint32_t usb_reg = NRF_POWER->USBREGSTATUS; + // Power module init const nrfx_power_config_t pwr_cfg = { 0 }; nrfx_power_init(&pwr_cfg); @@ -73,16 +81,7 @@ static void usb_hardware_init(void) nrfx_power_usbevt_enable(); - // Priorities 0, 1, 4 (nRF52) are reserved for SoftDevice - // 2 is highest for application - NVIC_SetPriority(USBD_IRQn, 2); - - // USB power may already be ready at this time -> no event generated - // We need to invoke the handler based on the status initially - uint32_t usb_reg = NRF_POWER->USBREGSTATUS; - if ( usb_reg & POWER_USBREGSTATUS_VBUSDETECT_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_DETECTED); - if ( usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk ) tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_READY); } // USB Device Driver task @@ -91,7 +90,7 @@ static void usb_device_task(void* param) { (void) param; - USBDevice.addInterface( (Adafruit_USBD_Interface&) Serial); + USBDevice.addInterface((Adafruit_USBD_Interface&) Serial); USBDevice.setID(USB_VID, USB_PID); USBDevice.begin(); @@ -111,7 +110,7 @@ static void usb_device_task(void* param) void Adafruit_TinyUSB_Core_init(void) { // Create a task for tinyusb device stack - xTaskCreate( usb_device_task, "usbd", USBD_STACK_SZ, NULL, TASK_PRIO_HIGH, NULL); + xTaskCreate(usb_device_task, "usbd", USBD_STACK_SZ, NULL, TASK_PRIO_HIGH, NULL); } void Adafruit_TinyUSB_Core_touch1200(void) diff --git a/cores/nRF5/TinyUSB/tusb_config.h b/cores/nRF5/TinyUSB/tusb_config.h index 3e7936ff..bf49dc3b 100644 --- a/cores/nRF5/TinyUSB/tusb_config.h +++ b/cores/nRF5/TinyUSB/tusb_config.h @@ -44,6 +44,10 @@ #define CFG_TUSB_MEM_SECTION #define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4))) +#ifndef CFG_TUSB_DEBUG +#define CFG_TUSB_DEBUG 0 +#endif + //-------------------------------------------------------------------- // DEVICE CONFIGURATION //-------------------------------------------------------------------- diff --git a/cores/nRF5/freertos/config/FreeRTOSConfig.h b/cores/nRF5/freertos/config/FreeRTOSConfig.h index e463dd30..bff583b4 100644 --- a/cores/nRF5/freertos/config/FreeRTOSConfig.h +++ b/cores/nRF5/freertos/config/FreeRTOSConfig.h @@ -139,8 +139,7 @@ #endif #endif /* !assembler */ -/* The lowest interrupt priority that can be used in a call to a "set priority" -function. */ +/* The lowest interrupt priority that can be used in a call to a "set priority" function. */ #define configLIBRARY_LOWEST_INTERRUPT_PRIORITY ((1< Ready event not yet handled + if ( (usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk) && (NRF_USBD->USBPULLUP == 0) ) + { + tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_READY); + } } #endif @@ -163,7 +174,7 @@ AdafruitBluefruit::AdafruitBluefruit(void) _ble_event_sem = NULL; _soc_event_sem = NULL; #ifdef ANT_LICENSE_KEY - _mprot_event_sem = NULL; //additiona semaphore for multiprotocol + _mprot_event_sem = NULL; #endif _led_blink_th = NULL; @@ -294,34 +305,31 @@ bool AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count) #if defined( USE_LFXO ) nrf_clock_lf_cfg_t clock_cfg = { - // LFXO - .source = NRF_CLOCK_LF_SRC_XTAL, - .rc_ctiv = 0, - .rc_temp_ctiv = 0, - .accuracy = NRF_CLOCK_LF_ACCURACY_20_PPM + // LFXO + .source = NRF_CLOCK_LF_SRC_XTAL, + .rc_ctiv = 0, + .rc_temp_ctiv = 0, + .accuracy = NRF_CLOCK_LF_ACCURACY_20_PPM }; #elif defined( USE_LFRC ) nrf_clock_lf_cfg_t clock_cfg = { - // LXRC - .source = NRF_CLOCK_LF_SRC_RC, - .rc_ctiv = 16, - .rc_temp_ctiv = 2, - .accuracy = NRF_CLOCK_LF_ACCURACY_250_PPM + // LXRC + .source = NRF_CLOCK_LF_SRC_RC, + .rc_ctiv = 16, + .rc_temp_ctiv = 2, + .accuracy = NRF_CLOCK_LF_ACCURACY_250_PPM }; #else #error Clock Source is not configured, define USE_LFXO or USE_LFRC according to your board in variant.h #endif - /*------------------------------------------------------------------ - ** BLE only Softdevices have 2-args sd_softdevice_enable() - ** BLE & ANT+ Softdevices have 3-args sd_softdevice_enable() - */ - #ifdef ANT_LICENSE_KEY + // Enable SoftDevice +#ifdef ANT_LICENSE_KEY VERIFY_STATUS( sd_softdevice_enable(&clock_cfg, nrf_error_cb, ANT_LICENSE_KEY), false ); -#else //#ifdef ANT_LICENSE_KEY +#else VERIFY_STATUS( sd_softdevice_enable(&clock_cfg, nrf_error_cb), false ); -#endif //#ifdef ANT_LICENSE_KEY +#endif #ifdef USE_TINYUSB usb_softdevice_post_enable(); @@ -464,13 +472,6 @@ bool AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count) ble_gap_conn_sec_mode_t sec_mode = BLE_SECMODE_OPEN; VERIFY_STATUS(sd_ble_gap_device_name_set(&sec_mode, (uint8_t const *) CFG_DEFAULT_NAME, strlen(CFG_DEFAULT_NAME)), false); - //------------- USB -------------// -#ifdef USE_TINYUSB - sd_power_usbdetected_enable(true); - sd_power_usbpwrrdy_enable(true); - sd_power_usbremoved_enable(true); -#endif - // Init Central role if (_central_count) Central.begin(); @@ -684,13 +685,21 @@ bool AdafruitBluefruit::setPIN(const char* pin) *------------------------------------------------------------------*/ void SD_EVT_IRQHandler(void) { - // Notify both BLE & SOC Task +#if CFG_SYSVIEW + SEGGER_SYSVIEW_RecordEnterISR(); +#endif + + // Notify both BLE & SOC & MultiProtocol (if any) Task xSemaphoreGiveFromISR(Bluefruit._soc_event_sem, NULL); xSemaphoreGiveFromISR(Bluefruit._ble_event_sem, NULL); + #ifdef ANT_LICENSE_KEY - // Notify parallel multiprotocol Task, if any if (Bluefruit._mprot_event_sem) xSemaphoreGiveFromISR(Bluefruit._mprot_event_sem, NULL); #endif + +#if CFG_SYSVIEW + SEGGER_SYSVIEW_RecordExitISR(); +#endif } /** From 29843dacb0c34c9ee151f1f05046d591544452a0 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Mon, 3 Aug 2020 01:40:29 -0700 Subject: [PATCH 29/76] Redefine tone() without ISR Other minor changes include: * Enable RTT option for output (requires platform.local.txt or boards.local.txt) * Allow setting compiler optimization (requires platform.local.txt or boards.local.txt) --- cores/nRF5/HardwarePWM.h | 2 + cores/nRF5/Tone.cpp | 522 +++++++++++++++++++++++++++++---------- cores/nRF5/Tone.h | 39 ++- cores/nRF5/main.cpp | 9 +- platform.txt | 7 +- 5 files changed, 450 insertions(+), 129 deletions(-) diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index 46bcd334..1afa0c37 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -117,6 +117,8 @@ class HardwarePWM #if CFG_DEBUG static void DebugOutput(Stream& logger); +#else + static void inline DebugOutput(Stream& logger) { (void)logger; }; #endif // CFG_DEBUG }; diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 9cdf312b..4aff6741 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -1,22 +1,22 @@ /* Tone.cpp - A Tone Generator Library +A Tone Generator Library - Written by Brett Hagman +Written by Brett Hagman - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version Modified By Date Comments ------- ----------- -------- -------- @@ -37,136 +37,408 @@ Version Modified By Date Comments #include "Arduino.h" #include "Tone.h" #include "WVariant.h" - -volatile unsigned long int count_duration=0; -volatile bool no_stop = false; -uint8_t pin_sound=0; -static uintptr_t _toneToken = 0x656e6f54; // 'T' 'o' 'n' 'e' +#include "limits.h" // NOTE: Currently hard-coded to only use PWM2 ... // These are the relvant hard-coded variables -// (plus the ISR PWM2_IRQHandler) -static IRQn_Type const _IntNo = PWM2_IRQn; +// TODO: Consider allowing dynamic use of any available PWM peripheral (but start with #2 for compatibility) static NRF_PWM_Type * const _PWMInstance = NRF_PWM2; static HardwarePWM * const _HwPWM = HwPWMx[2]; +// Defined a struct, to simplify validation testing ... also provides context when debugging +class TONE_PWM_CONFIG { + 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 + boolean is_initialized; //< defaults to uninitialized + + public: + bool EnsurePwmPeripheralOwnership(void) noexcept; + bool InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count, uint16_t time_period) noexcept; + bool ApplyConfiguration(uint32_t pin) noexcept; + bool StartPlayback(void) noexcept; + bool StopPlayback(bool releaseOwnership = false) noexcept; + bool ApplyConfigurationAndStartPlayback(uint32_t pin) noexcept; + uint64_t CalculateExpectedPulseCount(void) noexcept; +}; +TONE_PWM_CONFIG _pwm_config; + +inline static bool _is_pwm_enabled(NRF_PWM_Type const * pwm_instance) { + bool isEnabled = + (pwm_instance->ENABLE & PWM_ENABLE_ENABLE_Msk) == + (PWM_ENABLE_ENABLE_Enabled << PWM_ENABLE_ENABLE_Pos); + return isEnabled; +} + +/* These two functions were verified as equivalent to + the prior calculations (except where the old floating-point + based code resulted in rounding errors ... and thus there + are some one-off differences ... but the integer-based + functions are more accurate). + + These functions entirely avoid floating point math, and all + the nasty edge cases they can create... (NaN, INF, etc.) + + See https://gist.github.com/henrygab/6b570ebd51354bf247633c72b8dc383b + for code that compares the new lambdas to the old calculations. +*/ +constexpr inline static uint16_t _calculate_time_period(uint32_t frequency) throw() { + // range for frequency == [20..25000], + // so range of result == [ 5..62500] + // which fits in 16 bits. + return 125000 / frequency; +}; +constexpr inline static uint64_t _calculate_pulse_count(uint32_t frequency, uint32_t duration) throw() { + // range for frequency == [20..25000], + // range for duration == [ 1..0xFFFF_FFFF] + // so range of result == [ 1..0x18_FFFF_FFE7] (requires 37 bits) + static_assert(sizeof(unsigned long long) >= sizeof(uint64_t)); + return + (duration == 0) ? + 0 : + ((duration < 1000ULL) && (duration * frequency < 1000ULL)) ? + 1ULL : + (UINT64_MAX / frequency < duration) ? + (duration / 1000ULL) * frequency : + (((uint64_t)duration) * frequency / 1000ULL); +}; +inline static int _bits_used(unsigned long x) noexcept { + if (0 == x) return 0; + unsigned int result = 0; + do { + result++; + } while (x >>= 1); + return result; +} +inline static int _bits_used(unsigned long long x) noexcept { + if (0 == x) return 0; + unsigned int result = 0; + do { + result++; + } while (x >>= 1); + return result; +} + +/* +* In older versions of the BSP, tone() would cause an interrupt for every cycle, tracking whether +* the playback should be infinite or duration-based via two global, volatile variables, "nostop" +* and "count_duration". The interrupt would then trigger the STARTSEQ0 task, or stop playback +* by calling noTone(). +* +* What is available to configure looping with minimal memory usage: +* 1. SEQ[n].REFRESH === how many PWM period before loading next sample from sequence +* Thus, setting to 99 will cause 100 pulses per item +* Treat as a 23-bit value. +* 2. LOOP === how many times to loop back to SEQ[0] +* SEQ[0] will play the same count if started PWM at SEQ[0] +* SEQ[0] will play one fewer times if started PWM at SEQ[1] +* Treat as a 15-bit value. +* +* Therefore, between REFRESH and LOOP, can support up to 40-bit repeat WITHOUT INTERRUPTS. +* +* The value of duration is given in milliseconds. +* Frequency is limited to range [20 ... 25000]. +* +* Therefore, maximum pulse count is limited as follows: +* (32-bit duration) * (20 ... 25000) / 1000UL +* (0xFFFF_FFFF) * 25 +* 0x18_FFFF_FFE7 ... which is 37 bits +* +* Therefore, all possible values for tone() can be supported +* via a single one-time configuration of the PWM peripheral. +* +* PWM peripheral can be de-allocated by sketch call to noTone(). +* +* Design: +* 0. At each call to tone(), unconditionally stop any existing playback. +* 1. For infinite duration, configure large REFRESH and LOOP (to minimize reading of RAM / AHB traffic), +* and setup shortcut to repeat infinitely. +* 2. For specified duration, configure both SEQ0 and SEQ1: +* 1a. SEQ[1].REFRESH <-- total count % _iterations_per_loop +* 1b. SEQ[0].REFRESH <-- _iterations_per_loop - SEQ[1].CNT +* 1c. LOOP <-- duration_count / _iterations_per_loop +* +* Result: Zero CPU usage, minimal AHB traffic +*/ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) { - bool new_no_stop; - unsigned long int new_count_duration = (unsigned long int)-1L; - unsigned int time_per=0; + static_assert(sizeof(unsigned long int) <= sizeof(uint32_t)); + static_assert(sizeof(unsigned int) <= sizeof(uint32_t)); - // limit frequency to reasonable audible range - if((frequency < 20) | (frequency > 25000)) { - LOG_LV1("TON", "frequency outside range [20..25000] -- ignoring"); - return; - } - - // set nostop to true to avoid race condition. - // Specifically, race between a tone finishing - // after checking for ownership (which releases ownership) - // No effect if a tone is not playing.... - no_stop = true; - - // Use fixed PWM2 (due to need to connect interrupt) - if (!_HwPWM->isOwner(_toneToken) && - !_HwPWM->takeOwnership(_toneToken)) { - LOG_LV1("TON", "unable to allocate PWM2 to Tone"); - return; - } - - float per=float(1)/frequency; - time_per=per/0.000008; - unsigned int duty=time_per/2; - if(duration > 0) { - new_no_stop = false; - float mil=float(duration)/1000; - if(per>mil) { - new_count_duration = 1; - } else { - new_count_duration = mil/per; - } - } else { - new_no_stop = true; - } - - // Configure PWM - static uint16_t seq_values[]={0}; - //In each value, the most significant bit (15) determines the polarity of the output - //0x8000 is MSB = 1 - seq_values[0]= duty | 0x8000; - nrf_pwm_sequence_t const seq={ - seq_values, - NRF_PWM_VALUES_LENGTH(seq_values), - 0, - 0 + // Used only to protect calls against simultaneous multiple calls to tone(). + // Using a function-local static to avoid accidental reference from ISR or elsewhere, + // and to simplify ensuring the semaphore gets initialized. + static StaticSemaphore_t _tone_semaphore_allocation; + static auto init_semaphore = [] () throw() { //< use a lambda to both initialize AND give the mutex + SemaphoreHandle_t handle = xSemaphoreCreateBinaryStatic(&_tone_semaphore_allocation); + auto mustSucceed = xSemaphoreGive(handle); + (void)mustSucceed; + NRFX_ASSERT(mustSucceed == pdTRUE); + return handle; }; + static SemaphoreHandle_t _tone_semaphore = init_semaphore(); - uint32_t pins[NRF_PWM_CHANNEL_COUNT]={NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED, NRF_PWM_PIN_NOT_CONNECTED}; - pins[0] = g_ADigitalPinMap[pin]; + // limit frequency to reasonable audible range + if((frequency < 20) | (frequency > 25000)) { + LOG_LV1("TON", "frequency outside range [20..25000] -- ignoring"); + return; + } - // enable interrupt - count_duration = 0x6FFF; // large enough to avoid hitting zero in next few lines - no_stop = new_no_stop; + if(xSemaphoreTake(_tone_semaphore, portMAX_DELAY) != pdTRUE) { + LOG_LV1("TON", "error acquiring semaphore (should never occur?)"); + return; + } + uint64_t pulse_count = _calculate_pulse_count(frequency, duration); + uint16_t time_period = _calculate_time_period(frequency); - nrf_pwm_pins_set(_PWMInstance, pins); - nrf_pwm_enable(_PWMInstance); - nrf_pwm_configure(_PWMInstance, NRF_PWM_CLK_125kHz, NRF_PWM_MODE_UP, time_per); - nrf_pwm_decoder_set(_PWMInstance, NRF_PWM_LOAD_COMMON, NRF_PWM_STEP_AUTO); - nrf_pwm_sequence_set(_PWMInstance, 0, &seq); - nrf_pwm_shorts_enable(_PWMInstance, NRF_PWM_SHORT_SEQEND0_STOP_MASK); // shortcut for when SEQ0 ends, PWM output will automatically stop - nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_PWMPERIODEND); - nrf_pwm_int_enable(_PWMInstance, NRF_PWM_INT_PWMPERIODEND_MASK); - NVIC_SetPriority(_IntNo, 6); //low priority - NVIC_ClearPendingIRQ(_IntNo); - NVIC_EnableIRQ(_IntNo); - count_duration = new_count_duration; - nrf_pwm_task_trigger(_PWMInstance, NRF_PWM_TASK_SEQSTART0); + if (!_pwm_config.EnsurePwmPeripheralOwnership()) { + LOG_LV1("TON", "Unable to acquire PWM peripheral"); + } else if (!_pwm_config.StopPlayback()) { + LOG_LV1("TON", "Unable to stop playback"); + } else if (!_pwm_config.InitializeFromPulseCountAndTimePeriod(pulse_count, time_period)) { + LOG_LV1("TON", "Failed calculating configuration"); + } else if (!_pwm_config.ApplyConfiguration(pin)) { + LOG_LV1("TON", "Failed applying configuration"); + } else if (!_pwm_config.StartPlayback()) { + LOG_LV1("TON", "Failed attempting to start PWM peripheral"); + } else { + //LOG_LV2("TON", "Started playback of tone at frequency %d duration %ld", frequency, duration); + } + xSemaphoreGive(_tone_semaphore); + return; } - - void noTone(uint8_t pin) { - bool notInIsr = !isInISR(); - - if (!_HwPWM->isOwner(_toneToken)) { - if (notInIsr) { - LOG_LV1("TON", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); - } - return; - } - nrf_pwm_task_trigger(_PWMInstance, NRF_PWM_TASK_STOP); - nrf_pwm_disable(_PWMInstance); - _PWMInstance->PSEL.OUT[0] = NRF_PWM_PIN_NOT_CONNECTED; - NVIC_DisableIRQ(_IntNo); - _HwPWM->releaseOwnership(_toneToken); - if (_HwPWM->isOwner(_toneToken)) { - if (notInIsr) { - LOG_LV1("TON", "stopped tone, but failed to release ownership of PWM peripheral?"); - } - return; - } + ( void )pin; // avoid unreferenced parameter compiler warning + _pwm_config.StopPlayback(true); // release ownership of PWM peripheral } -#ifdef __cplusplus -extern "C"{ -#endif - -void PWM2_IRQHandler(void){ - nrf_pwm_event_clear(NRF_PWM2, NRF_PWM_EVENT_PWMPERIODEND); - if(!no_stop){ - count_duration--; - if(count_duration == 0) { - uint8_t pin = _PWMInstance->PSEL.OUT[0]; - noTone(pin); - } else { - nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_SEQSTART0); - } - } else { - nrf_pwm_task_trigger(NRF_PWM2, NRF_PWM_TASK_SEQSTART0); - } +bool TONE_PWM_CONFIG::EnsurePwmPeripheralOwnership(void) { + if (!_HwPWM->isOwner(TONE_PWM_CONFIG::toneToken) && !_HwPWM->takeOwnership(TONE_PWM_CONFIG::toneToken)) { + LOG_LV1("TON", "unable to allocate PWM2 to Tone"); + return false; + } + return true; } -#ifdef __cplusplus +// +// The final loop's SEQ1 will ALWAYS output one pulse ... +// In other words, SEQ1's refresh is *IGNORED* for the final loop. +// +// Visually, with each sequence length set to one as is done with tone(): +// ====================================================================== +// +// Starting at SEQ0, loopCnt = 2, SEQ0 refresh == 4, SEQ1 refresh = 2: +// +// [----SEQ0-----] [SEQ1-] [----SEQ0-----] [1] +// 0 0 0 0 1 1 0 0 0 0 1 +// +// ====================================================================== +// +// Starting as SEQ1, loopCnt = 2, SEQ0 refresh == 4, SEQ1 refresh = 2: +// +// [SEQ1-] [----SEQ0-----] [1] +// 1 1 0 0 0 0 1 +// +// ====================================================================== +// +// Therefore, the total count of pulses that will be emitted by the +// PWM peripheral (per the configuration of tone() API): +// +// COUNT = (SEQ0.CNT * (SEQ0.REFRESH+1); +// COUNT += (SEQ1.CNT * (SEQ1.REFRESH+1); +// COUNT *= (loopCount-1); // the number of times SEQ0 and SEQ1 both run +// COUNT += (start at SEQ0) ? (SEQ0.CNT * (SEQ0.REFRESH+1) : 0; +// COUNT += 1; // final SEQ1 emits single pulse +// +bool TONE_PWM_CONFIG::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count_x, uint16_t time_period) noexcept { + + if (_bits_used(pulse_count_x) > 37) { + LOG_LV1("TON", "pulse count is limited to 37 bit long value"); + return false; + } + + this->pulse_count = pulse_count_x; + this->time_period = time_period; + this->duty_with_polarity = 0x8000U | (time_period / 2U); + + if (this->pulse_count == 0) { + LOG_LV3("TON", "Infinite duration requested\n"); + + this->seq0_refresh = 0xFFFFFFU; // 24-bit maximum value + this->seq1_refresh = 0xFFFFFFU; // 24-bit maximum value + this->loop_count = 0xFFFFU; // 16-bit maximum value + this->task_to_start = NRF_PWM_TASK_SEQSTART0; + this->shorts = NRF_PWM_SHORT_LOOPSDONE_SEQSTART0_MASK; + } + else if (this->pulse_count == 1) { + LOG_LV3("TON", "Edge case: exactly one pulse\n"); + // yes, this is an edge case + this->seq0_refresh = 0; + this->seq1_refresh = 0; + this->loop_count = 1; + this->task_to_start = NRF_PWM_TASK_SEQSTART1; + this->shorts = NRF_PWM_SHORT_LOOPSDONE_STOP_MASK; + } + else { + LOG_LV3("TON", "Non-infinite duration of at least two pulses requested\n"); + + // This is the interesting section. + // + // To ensure refresh value stays within 24 bits, the maximum number of bits + // for the pulse_count is ((24 * 3) / 2) + 1 == (72/2) + 1 == 36 + 1 == 37. + // + // Validation: + // 37 * 2 / 3 == 74 / 3 == 24 (OK) -- leaves 13 bits for loop count + // 38 * 2 / 3 == 76 / 3 == 25 (fail) -- leaves 13 bits for loop count + // + // NOTE: theoretically possible to support up to 40 bit pulse count, but + // would require more complex logic. + // + unsigned int bits_needed = _bits_used(this->pulse_count); // bits_used is now in range [2..37] + + // split the number of bits between refresh and loop_count in 2:1 ratio + // so that, no matter what inputs are given, guaranteed to have interrupt-free solution + unsigned int bits_for_refresh = bits_needed * 2 / 3; // range is [1 .. 24] + unsigned int bits_for_loop_count = bits_needed - bits_for_refresh; // range is [1 .. 13] + + // NOTE: Due to final SEQ1 outputting exactly one pulse, may need one additional bit for loop count + // ... but that will still be within the 16 bits available, because top of range is 13 bits. + LOG_LV3("TON", "Using %d bits for refresh, and %d bits for loop_count\n", bits_for_refresh, bits_for_loop_count); + + // now determine how many PWM pulses should occur per loop (when both SEQ0 and SEQ1 are played) + uint32_t total_refresh_count = 1 << bits_for_refresh; // range is [2 .. 2^24] + uint32_t full_loops = (this->pulse_count - 1) / total_refresh_count; // == loopCount - 1 + + LOG_LV3("TON", "total_refresh_count is 0x%" PRIx32 " (%" PRIu32 ")\n", total_refresh_count, total_refresh_count); + LOG_LV3("TON", "full_loops is 0x%" PRIx32 " (%" PRIu32 ")\n", full_loops, full_loops); + + // if (pulses - 1) % total_refresh_count == 0, then start at SEQ1 and split refresh evenly + // else, start at SEQ0, and set SEQ0 to extra pulses needed... + uint32_t extraPulsesNeededIfStartingAtSequence1 = (this->pulse_count - 1) % total_refresh_count; + uint32_t seq0_count; + + if (extraPulsesNeededIfStartingAtSequence1 == 0) { + LOG_LV3("TON", "Pulse count (minus one) is exact multiple of total_refresh_count -- starting at SEQ1\n"); + seq0_count = total_refresh_count / 2; // range is [1 .. 2^23] + this->task_to_start = NRF_PWM_TASK_SEQSTART1; + } + else { + LOG_LV3("TON", "Pulse count (minus one) requires extra %" PRIu32 " pulses ... setting SEQ0 to that value\n", extraPulsesNeededIfStartingAtSequence1); + seq0_count = extraPulsesNeededIfStartingAtSequence1; + this->task_to_start = NRF_PWM_TASK_SEQSTART0; + } + this->loop_count = full_loops + 1; + this->seq0_refresh = seq0_count - 1; + this->seq1_refresh = (total_refresh_count - seq0_count) - 1; + + LOG_LV3("TON", "seq0_count is %" PRIu32 ", so refresh will be set to %" PRIu32 "\n", seq0_count, this->seq0_refresh); + LOG_LV3("TON", "seq1_count is %" PRIu32 ", so refresh will be set to %" PRIu32 "\n", (total_refresh_count - seq0_count), this->seq1_refresh); + + this->shorts = NRF_PWM_SHORT_LOOPSDONE_STOP_MASK; + } + this->is_initialized = true; + return true; +} +bool TONE_PWM_CONFIG::ApplyConfiguration(uint32_t pin) noexcept { + if (!this->is_initialized) { + return false; + } + if (pin >= PINS_COUNT) { + return false; + } + if (!this->EnsurePwmPeripheralOwnership()) { + return false; + } + this->StopPlayback(false); + + this->arduino_pin = pin; + this->nrf_pin = g_ADigitalPinMap[pin]; + + uint32_t pins[NRF_PWM_CHANNEL_COUNT] = { + this->nrf_pin, + NRF_PWM_PIN_NOT_CONNECTED, + NRF_PWM_PIN_NOT_CONNECTED, + NRF_PWM_PIN_NOT_CONNECTED + }; + + nrf_pwm_pins_set(_PWMInstance, pins); // must set pins before enabling + nrf_pwm_enable(_PWMInstance); + nrf_pwm_configure(_PWMInstance, TONE_PWM_CONFIG::clock_frequency, TONE_PWM_CONFIG::pwm_mode, this->time_period); + nrf_pwm_decoder_set(_PWMInstance, TONE_PWM_CONFIG::load_mode, TONE_PWM_CONFIG::step_mode); + 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[1] = { this->duty_with_polarity }; + + nrf_pwm_seq_ptr_set(_PWMInstance, 0, &seq_values[0]); + nrf_pwm_seq_ptr_set(_PWMInstance, 1, &seq_values[0]); + nrf_pwm_seq_cnt_set(_PWMInstance, 0, 1); + nrf_pwm_seq_cnt_set(_PWMInstance, 1, 1); + + nrf_pwm_seq_refresh_set(_PWMInstance, 0, seq0_refresh); + nrf_pwm_seq_refresh_set(_PWMInstance, 1, seq1_refresh); + nrf_pwm_seq_end_delay_set(_PWMInstance, 0, 0); + nrf_pwm_seq_end_delay_set(_PWMInstance, 1, 0); + nrf_pwm_loop_set(_PWMInstance, loop_count); + + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_STOPPED); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_SEQSTARTED0); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_SEQSTARTED1); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_SEQEND0); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_SEQEND1); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_PWMPERIODEND); + nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_LOOPSDONE); + return true; +} +bool TONE_PWM_CONFIG::StartPlayback(void) noexcept { + if (!this->is_initialized) { + LOG_LV1("TON", "Cannot start playback without first initializing"); + return false; + } + if (!this->EnsurePwmPeripheralOwnership()) { + LOG_LV1("TON", "PWM peripheral not available for playback"); + return false; + } + nrf_pwm_task_trigger(_PWMInstance, this->task_to_start); + return true; +} +bool TONE_PWM_CONFIG::StopPlayback(bool releaseOwnership) { + + bool notInIsr = !isInISR(); + + if (!_HwPWM->isOwner(TONE_PWM_CONFIG::toneToken)) { + if (notInIsr) { + 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)) { + nrf_pwm_task_trigger(_PWMInstance, NRF_PWM_TASK_STOP); + nrf_pwm_disable(_PWMInstance); + _PWMInstance->PSEL.OUT[0] = NRF_PWM_PIN_NOT_CONNECTED; + } + + if (releaseOwnership) { + _HwPWM->releaseOwnership(TONE_PWM_CONFIG::toneToken); + } + return true; } -#endif diff --git a/cores/nRF5/Tone.h b/cores/nRF5/Tone.h index 8874a1ce..064cfad3 100644 --- a/cores/nRF5/Tone.h +++ b/cores/nRF5/Tone.h @@ -15,6 +15,7 @@ License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ +/** \file Tone.h */ #ifndef _WIRING_TONE_ #define _WIRING_TONE_ @@ -25,8 +26,44 @@ #include "wiring_digital.h" #include "nrf_pwm.h" - +/** + * \brief Generate a tone (PWM) output on the specified pin. + * + * \param[in] pin The Arduino pin for output + * + * \param[in] frequency The frequency, in hertz, of the requested tone. + * + * \param[in] duration An optional duration, in milliseconds (default: 0 == infinite) + * + * Generates a square wave of the specified frequency (and 50% duty cycle) + * on a pin. A duration can be specified, otherwise the wave continues until a call + * to `noTone()`. The pin can be connected to a piezo buzzer or other speaker to + * play tones. + * + * The `tone()` API has the following contracts, which were defined by + * the original Arduino code: + * + * 1. at most one `tone()` can be generated at a time + * 2. so long as the `pin` stays the same, `tone()` can be called repeatedly + * 3. a call to `noTone()` is required prior to calling `tone()` with a different pin. + * + * The third requirement is not enforced in the nRF52 BSP. Instead, if a call + * to `tone()` is made with a different pin, a call to `noTone()` occurs automatically, + * simplifying use somewhat. + * + * For the nRF52, the allowed range for parameter `frequency` is `[20..25000]`. + * + * \see noTone + */ void tone(uint8_t pin, unsigned int frequency, unsigned long duration = 0); +/** + * \brief Stops generation of a tone (PWM) output. + * + * \param pin For the nRF52, this argument is ignored + * + * Stops the generation of a square wave triggered by `tone()`. + * This function has no effect if no tone is being generated. + */ void noTone(uint8_t pin); diff --git a/cores/nRF5/main.cpp b/cores/nRF5/main.cpp index 98e3a291..18e7432c 100644 --- a/cores/nRF5/main.cpp +++ b/cores/nRF5/main.cpp @@ -15,6 +15,9 @@ #define ARDUINO_MAIN #include "Arduino.h" +#if (CFG_LOGGER == 2) + #include +#endif // DEBUG Level 1 #if CFG_DEBUG @@ -106,11 +109,15 @@ extern "C" int _write (int fd, const void *buf, size_t count) { (void) fd; - +#if (CFG_LOGGER == 2) + unsigned numBytes = count; + SEGGER_RTT_Write(0, buf, numBytes); +#else if ( Serial ) { return Serial.write( (const uint8_t *) buf, count); } +#endif return 0; } diff --git a/platform.txt b/platform.txt index f8f47382..ce3cd4b9 100644 --- a/platform.txt +++ b/platform.txt @@ -28,11 +28,14 @@ compiler.warning_flags.default= compiler.warning_flags.more=-Wall compiler.warning_flags.all=-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -Wno-pointer-arith +# Allow changing optimization settings via platform.local.txt / boards.local.txt +compiler.optimization_flag=-Ofast + compiler.path={runtime.tools.arm-none-eabi-gcc.path}/bin/ compiler.c.cmd=arm-none-eabi-gcc compiler.c.flags=-mcpu={build.mcu} -mthumb -c -g {compiler.warning_flags} {build.float_flags} -std=gnu11 -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -MMD compiler.c.elf.cmd=arm-none-eabi-gcc -compiler.c.elf.flags=-Ofast -Wl,--gc-sections -save-temps +compiler.c.elf.flags={compiler.optimization_flag} -Wl,--gc-sections -save-temps compiler.S.cmd=arm-none-eabi-gcc compiler.S.flags=-c -g -x assembler-with-cpp compiler.cpp.cmd=arm-none-eabi-g++ @@ -60,7 +63,7 @@ nordic.path={build.core.path}/nordic # build.logger_flags and build.sysview_flags and intentionally empty, # to allow modification via a user's own boards.local.txt or platform.local.txt files. -build.flags.nrf= -DSOFTDEVICE_PRESENT -DARDUINO_NRF52_ADAFRUIT -DNRF52_SERIES -DLFS_NAME_MAX=64 -Ofast {build.debug_flags} {build.logger_flags} {build.sysview_flags} "-I{build.core.path}/cmsis/Core/Include" "-I{nordic.path}" "-I{nordic.path}/nrfx" "-I{nordic.path}/nrfx/hal" "-I{nordic.path}/nrfx/mdk" "-I{nordic.path}/nrfx/soc" "-I{nordic.path}/nrfx/drivers/include" "-I{nordic.path}/nrfx/drivers/src" "-I{nordic.path}/softdevice/{build.sd_name}_nrf52_{build.sd_version}_API/include" "-I{nordic.path}/softdevice/{build.sd_name}_nrf52_{build.sd_version}_API/include/nrf52" "-I{rtos.path}/Source/include" "-I{rtos.path}/config" "-I{rtos.path}/portable/GCC/nrf52" "-I{rtos.path}/portable/CMSIS/nrf52" "-I{build.core.path}/sysview/SEGGER" "-I{build.core.path}/sysview/Config" "-I{build.core.path}/TinyUSB" "-I{build.core.path}/TinyUSB/Adafruit_TinyUSB_ArduinoCore" "-I{build.core.path}/TinyUSB/Adafruit_TinyUSB_ArduinoCore/tinyusb/src" +build.flags.nrf= -DSOFTDEVICE_PRESENT -DARDUINO_NRF52_ADAFRUIT -DNRF52_SERIES -DLFS_NAME_MAX=64 {compiler.optimization_flag} {build.debug_flags} {build.logger_flags} {build.sysview_flags} "-I{build.core.path}/cmsis/Core/Include" "-I{nordic.path}" "-I{nordic.path}/nrfx" "-I{nordic.path}/nrfx/hal" "-I{nordic.path}/nrfx/mdk" "-I{nordic.path}/nrfx/soc" "-I{nordic.path}/nrfx/drivers/include" "-I{nordic.path}/nrfx/drivers/src" "-I{nordic.path}/softdevice/{build.sd_name}_nrf52_{build.sd_version}_API/include" "-I{nordic.path}/softdevice/{build.sd_name}_nrf52_{build.sd_version}_API/include/nrf52" "-I{rtos.path}/Source/include" "-I{rtos.path}/config" "-I{rtos.path}/portable/GCC/nrf52" "-I{rtos.path}/portable/CMSIS/nrf52" "-I{build.core.path}/sysview/SEGGER" "-I{build.core.path}/sysview/Config" "-I{build.core.path}/TinyUSB" "-I{build.core.path}/TinyUSB/Adafruit_TinyUSB_ArduinoCore" "-I{build.core.path}/TinyUSB/Adafruit_TinyUSB_ArduinoCore/tinyusb/src" # usb flags build.flags.usb= -DUSBCON -DUSE_TINYUSB -DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}' From e200ee88debf120796411ba17551455429399d20 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Mon, 3 Aug 2020 02:32:08 -0700 Subject: [PATCH 30/76] Remove deeper debug level 3 --- cores/nRF5/HardwarePWM.cpp | 9 --------- cores/nRF5/Tone.cpp | 17 +---------------- cores/nRF5/common_func.h | 8 -------- cores/nRF5/wiring_analog.cpp | 3 --- 4 files changed, 1 insertion(+), 36 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 30622044..e29f538a 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -110,21 +110,12 @@ bool HardwarePWM::takeOwnership(uintptr_t token) } } if (this->_owner_token != 0) { - if (notInIsr) { - LOG_LV3("HwPWM", "failing to acquire ownership because already owned by other token"); - } return false; } if (this->usedChannelCount() != 0) { - if (notInIsr) { - LOG_LV3("HwPWM", "failing to acquire ownership because at least one channel connected"); - } return false; } if (this->enabled()) { - if (notInIsr) { - LOG_LV3("HwPWM", "failing to acquire ownership because peripheral is already enabled"); - } return false; } // TODO: warn, but do not fail, if taking ownership with IRQs already enabled diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 4aff6741..70e365ba 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -277,8 +277,6 @@ bool TONE_PWM_CONFIG::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count this->duty_with_polarity = 0x8000U | (time_period / 2U); if (this->pulse_count == 0) { - LOG_LV3("TON", "Infinite duration requested\n"); - this->seq0_refresh = 0xFFFFFFU; // 24-bit maximum value this->seq1_refresh = 0xFFFFFFU; // 24-bit maximum value this->loop_count = 0xFFFFU; // 16-bit maximum value @@ -286,8 +284,7 @@ bool TONE_PWM_CONFIG::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count this->shorts = NRF_PWM_SHORT_LOOPSDONE_SEQSTART0_MASK; } else if (this->pulse_count == 1) { - LOG_LV3("TON", "Edge case: exactly one pulse\n"); - // yes, this is an edge case + // yes, this is an edge case; e.g., frequency == 100, duration == 100 causes this this->seq0_refresh = 0; this->seq1_refresh = 0; this->loop_count = 1; @@ -295,8 +292,6 @@ bool TONE_PWM_CONFIG::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count this->shorts = NRF_PWM_SHORT_LOOPSDONE_STOP_MASK; } else { - LOG_LV3("TON", "Non-infinite duration of at least two pulses requested\n"); - // This is the interesting section. // // To ensure refresh value stays within 24 bits, the maximum number of bits @@ -318,37 +313,27 @@ bool TONE_PWM_CONFIG::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count // NOTE: Due to final SEQ1 outputting exactly one pulse, may need one additional bit for loop count // ... but that will still be within the 16 bits available, because top of range is 13 bits. - LOG_LV3("TON", "Using %d bits for refresh, and %d bits for loop_count\n", bits_for_refresh, bits_for_loop_count); // now determine how many PWM pulses should occur per loop (when both SEQ0 and SEQ1 are played) uint32_t total_refresh_count = 1 << bits_for_refresh; // range is [2 .. 2^24] uint32_t full_loops = (this->pulse_count - 1) / total_refresh_count; // == loopCount - 1 - LOG_LV3("TON", "total_refresh_count is 0x%" PRIx32 " (%" PRIu32 ")\n", total_refresh_count, total_refresh_count); - LOG_LV3("TON", "full_loops is 0x%" PRIx32 " (%" PRIu32 ")\n", full_loops, full_loops); - // if (pulses - 1) % total_refresh_count == 0, then start at SEQ1 and split refresh evenly // else, start at SEQ0, and set SEQ0 to extra pulses needed... uint32_t extraPulsesNeededIfStartingAtSequence1 = (this->pulse_count - 1) % total_refresh_count; uint32_t seq0_count; if (extraPulsesNeededIfStartingAtSequence1 == 0) { - LOG_LV3("TON", "Pulse count (minus one) is exact multiple of total_refresh_count -- starting at SEQ1\n"); seq0_count = total_refresh_count / 2; // range is [1 .. 2^23] this->task_to_start = NRF_PWM_TASK_SEQSTART1; } else { - LOG_LV3("TON", "Pulse count (minus one) requires extra %" PRIu32 " pulses ... setting SEQ0 to that value\n", extraPulsesNeededIfStartingAtSequence1); seq0_count = extraPulsesNeededIfStartingAtSequence1; this->task_to_start = NRF_PWM_TASK_SEQSTART0; } this->loop_count = full_loops + 1; this->seq0_refresh = seq0_count - 1; this->seq1_refresh = (total_refresh_count - seq0_count) - 1; - - LOG_LV3("TON", "seq0_count is %" PRIu32 ", so refresh will be set to %" PRIu32 "\n", seq0_count, this->seq0_refresh); - LOG_LV3("TON", "seq1_count is %" PRIu32 ", so refresh will be set to %" PRIu32 "\n", (total_refresh_count - seq0_count), this->seq1_refresh); - this->shorts = NRF_PWM_SHORT_LOOPSDONE_STOP_MASK; } this->is_initialized = true; diff --git a/cores/nRF5/common_func.h b/cores/nRF5/common_func.h index c6229b8a..ad42c626 100644 --- a/cores/nRF5/common_func.h +++ b/cores/nRF5/common_func.h @@ -172,14 +172,6 @@ const char* dbg_err_str(int32_t err_id); // TODO move to other place #define LOG_LV2_BUFFER(...) #endif -#if CFG_DEBUG >= 3 -#define LOG_LV3(...) ADALOG(__VA_ARGS__) -#define LOG_LV3_BUFFER(...) ADALOG_BUFFER(__VA_ARGS__) -#else -#define LOG_LV3(...) -#define LOG_LV3_BUFFER(...) -#endif - #if CFG_DEBUG #define PRINT_LOCATION() PRINTF("%s: %d:\n", __PRETTY_FUNCTION__, __LINE__) diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 5267a64c..7c1ac04f 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -96,11 +96,9 @@ void analogWrite( uint32_t pin, uint32_t value ) for(int i=0; iisOwner(_analogToken)) { - LOG_LV3("ANA", "not currently owner of PWM %d", i); continue; } if (!HwPWMx[i]->addPin(pin)) { - LOG_LV3("ANA", "could not add pin %" PRIu32 " to PWM %d", pin, i); continue; } @@ -116,7 +114,6 @@ void analogWrite( uint32_t pin, uint32_t value ) for(int i=0; itakeOwnership(_analogToken)) { - LOG_LV3("ANA", "Could not take ownership of PWM %d", i); continue; } From b54bcf3df63bfe6a59537a8442d1f2e85ce0f85f Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 3 Aug 2020 22:17:40 +0700 Subject: [PATCH 31/76] a few delay before enter dfu by touch1200 --- cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp b/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp index e4f50237..0ecfffa6 100644 --- a/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp +++ b/cores/nRF5/TinyUSB/Adafruit_TinyUSB_nRF.cpp @@ -116,6 +116,7 @@ void Adafruit_TinyUSB_Core_init(void) void Adafruit_TinyUSB_Core_touch1200(void) { + delay(5); // a few millisecond for USB control status completion enterSerialDfu(); } From 24f39073daa4c189b6791c22df73821399b24386 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 4 Aug 2020 14:52:45 +0700 Subject: [PATCH 32/76] update tinyusb core to commit c36ecdaf54aaa88cb678f05ea973d6795f2d6cae --- cores/nRF5/TinyUSB/Adafruit_TinyUSB_ArduinoCore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cores/nRF5/TinyUSB/Adafruit_TinyUSB_ArduinoCore b/cores/nRF5/TinyUSB/Adafruit_TinyUSB_ArduinoCore index 238a5c0b..c36ecdaf 160000 --- a/cores/nRF5/TinyUSB/Adafruit_TinyUSB_ArduinoCore +++ b/cores/nRF5/TinyUSB/Adafruit_TinyUSB_ArduinoCore @@ -1 +1 @@ -Subproject commit 238a5c0b95fcd402d24524c7bebbdd822168a51e +Subproject commit c36ecdaf54aaa88cb678f05ea973d6795f2d6cae From c25d93268a3b9c23e9a1ccfcaf9b208beca624ca Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 4 Aug 2020 16:34:09 +0700 Subject: [PATCH 33/76] fix warnings --- libraries/Adafruit_LittleFS/src/littlefs/lfs_util.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libraries/Adafruit_LittleFS/src/littlefs/lfs_util.h b/libraries/Adafruit_LittleFS/src/littlefs/lfs_util.h index e992ee6f..14e26530 100644 --- a/libraries/Adafruit_LittleFS/src/littlefs/lfs_util.h +++ b/libraries/Adafruit_LittleFS/src/littlefs/lfs_util.h @@ -168,6 +168,7 @@ void lfs_crc(uint32_t *crc, const void *buffer, size_t size); // Allocate memory, only used if buffers are not provided to littlefs static inline void *lfs_malloc(size_t size) { #ifndef LFS_NO_MALLOC + extern void *pvPortMalloc( size_t xWantedSize ); return pvPortMalloc(size); #else (void)size; @@ -178,6 +179,7 @@ static inline void *lfs_malloc(size_t size) { // Deallocate memory, only used if buffers are not provided to littlefs static inline void lfs_free(void *p) { #ifndef LFS_NO_MALLOC + extern void vPortFree( void *pv ); vPortFree(p); #else (void)p; From ccd2fe3ca3f46b58455695e3bdf91a4fe41e3cff Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 5 Aug 2020 16:46:16 +0700 Subject: [PATCH 34/76] micro() use DWT cyclecount if enabled else use rtos tick DWT must be previously enabled by user sketch with dwt_enable() --- cores/nRF5/delay.c | 5 ----- cores/nRF5/delay.h | 14 +++++++++++++- .../portable/CMSIS/nrf52/port_cmsis_systick.c | 6 ++++++ 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/cores/nRF5/delay.c b/cores/nRF5/delay.c index f96d5058..73c68e1d 100644 --- a/cores/nRF5/delay.c +++ b/cores/nRF5/delay.c @@ -30,11 +30,6 @@ uint32_t millis( void ) return tick2ms(xTaskGetTickCount()); } -uint32_t micros( void ) -{ - return tick2us(xTaskGetTickCount()); -} - void delay( uint32_t ms ) { uint32_t ticks = ms2tick(ms); diff --git a/cores/nRF5/delay.h b/cores/nRF5/delay.h index f25809f7..404334ba 100644 --- a/cores/nRF5/delay.h +++ b/cores/nRF5/delay.h @@ -26,6 +26,13 @@ extern "C" { #include #include "nrfx.h" #include "variant.h" +#include "rtos.h" + +static inline bool dwt_enabled(void) __attribute__((always_inline)); +static inline bool dwt_enabled(void) +{ + return (CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk) && (DWT->CTRL & DWT_CTRL_CYCCNTENA_Msk); +} /** * \brief Returns the number of milliseconds since the Arduino board began running the current program. @@ -46,7 +53,12 @@ extern uint32_t millis( void ) ; * * \note There are 1,000 microseconds in a millisecond and 1,000,000 microseconds in a second. */ -extern uint32_t micros( void ) ; +static inline uint32_t micros( void ) __attribute__((always_inline)); +static inline uint32_t micros( void ) +{ + // Use DWT cycle count if it is enabled, otherwise use rtos tick + return dwt_enabled() ? (DWT->CYCCNT / 64) : tick2us(xTaskGetTickCount()); +} /** * \brief Pauses the program for the amount of time (in miliseconds) specified as parameter. diff --git a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c index 21dec1fc..8f60b2c3 100644 --- a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c +++ b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c @@ -230,6 +230,12 @@ void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) if (diff > 0) { vTaskStepTick(diff); + + // If dwt cycle count is enable, adjust it as welll + if ( (CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk) && (DWT->CTRL & DWT_CTRL_CYCCNTENA_Msk) ) + { + DWT->CYCCNT += ((diff * 1000000) / configTICK_RATE_HZ) * 64; + } } } } From 68a9302a79be30df27acab2cb0a72b5cf119c411 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sat, 8 Aug 2020 11:20:36 -0700 Subject: [PATCH 35/76] Fix off-by-one typo --- cores/nRF5/Tone.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 70e365ba..ac85f27a 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -309,7 +309,7 @@ bool TONE_PWM_CONFIG::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count // split the number of bits between refresh and loop_count in 2:1 ratio // so that, no matter what inputs are given, guaranteed to have interrupt-free solution unsigned int bits_for_refresh = bits_needed * 2 / 3; // range is [1 .. 24] - unsigned int bits_for_loop_count = bits_needed - bits_for_refresh; // range is [1 .. 13] + //unsigned int bits_for_loop_count = bits_needed - bits_for_refresh; // range is [1 .. 13] // NOTE: Due to final SEQ1 outputting exactly one pulse, may need one additional bit for loop count // ... but that will still be within the 16 bits available, because top of range is 13 bits. @@ -371,10 +371,11 @@ bool TONE_PWM_CONFIG::ApplyConfiguration(uint32_t pin) noexcept { // 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[1] = { this->duty_with_polarity }; + static uint16_t seq_values; // static value + seq_values = this->duty_with_polarity; - nrf_pwm_seq_ptr_set(_PWMInstance, 0, &seq_values[0]); - nrf_pwm_seq_ptr_set(_PWMInstance, 1, &seq_values[0]); + nrf_pwm_seq_ptr_set(_PWMInstance, 0, &seq_values); + nrf_pwm_seq_ptr_set(_PWMInstance, 1, &seq_values); nrf_pwm_seq_cnt_set(_PWMInstance, 0, 1); nrf_pwm_seq_cnt_set(_PWMInstance, 1, 1); From a566c693d9fbea5f97137b8a92e36b76cb05226e Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Tue, 11 Aug 2020 20:20:49 -0700 Subject: [PATCH 36/76] With no ISR, use Mutex (not Binary) semaphore --- cores/nRF5/Tone.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index ac85f27a..2b04688e 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -184,7 +184,7 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) // and to simplify ensuring the semaphore gets initialized. static StaticSemaphore_t _tone_semaphore_allocation; static auto init_semaphore = [] () throw() { //< use a lambda to both initialize AND give the mutex - SemaphoreHandle_t handle = xSemaphoreCreateBinaryStatic(&_tone_semaphore_allocation); + SemaphoreHandle_t handle = xSemaphoreCreateMutexStatic(&_tone_semaphore_allocation); auto mustSucceed = xSemaphoreGive(handle); (void)mustSucceed; NRFX_ASSERT(mustSucceed == pdTRUE); From e99b5ea40e7649fb582f2492d7f4ccc303c9f620 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Tue, 11 Aug 2020 22:24:37 -0700 Subject: [PATCH 37/76] Use C++11 atomic --- cores/nRF5/HardwarePWM.cpp | 12 ++++++------ cores/nRF5/HardwarePWM.h | 3 ++- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index e29f538a..6acf51ec 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -121,9 +121,9 @@ bool HardwarePWM::takeOwnership(uintptr_t token) // TODO: warn, but do not fail, if taking ownership with IRQs already enabled // NVIC_GetActive - // 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); + // 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) @@ -156,9 +156,8 @@ bool HardwarePWM::releaseOwnership(uintptr_t token) // TODO: warn, but do not fail, if releasing ownership with IRQs enabled // NVIC_GetActive - // use gcc built-in intrinsic to ensure atomicity - // See https://gcc.gnu.org/onlinedocs/gcc/_005f_005fsync-Builtins.html - bool result = __sync_bool_compare_and_swap(&(this->_owner_token), token, 0); + // 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"); } @@ -168,6 +167,7 @@ bool HardwarePWM::releaseOwnership(uintptr_t token) HardwarePWM::HardwarePWM(NRF_PWM_Type* pwm) : _pwm(pwm) { + _owner_token = 0U; arrclr(_seq0); _max_value = 255; diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index 1afa0c37..c2d8f4e4 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; - volatile uintptr_t _owner_token = 0; + std::atomic_uintptr_t _owner_token; uint16_t _seq0[MAX_CHANNELS]; From 02045e3b300d00569c6d6acc4e121d65fef41a6a Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Tue, 11 Aug 2020 22:35:19 -0700 Subject: [PATCH 38/76] Poe-tay-toe, poe-tah-toe --- cores/nRF5/HardwarePWM.cpp | 2 ++ cores/nRF5/HardwarePWM.h | 4 ---- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 6acf51ec..f9927727 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -92,6 +92,8 @@ void HardwarePWM::DebugOutput(Stream& logger) } logger.printf("\n"); } +#else +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 diff --git a/cores/nRF5/HardwarePWM.h b/cores/nRF5/HardwarePWM.h index c2d8f4e4..024a8c84 100644 --- a/cores/nRF5/HardwarePWM.h +++ b/cores/nRF5/HardwarePWM.h @@ -116,11 +116,7 @@ class HardwarePWM uint8_t usedChannelCount(void) const; uint8_t freeChannelCount(void) const; -#if CFG_DEBUG static void DebugOutput(Stream& logger); -#else - static void inline DebugOutput(Stream& logger) { (void)logger; }; -#endif // CFG_DEBUG }; extern HardwarePWM HwPWM0; From fdf405c1ba88da5ee4f4626e167ec9f3a84b7cd7 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Tue, 11 Aug 2020 22:57:50 -0700 Subject: [PATCH 39/76] @hathach believes having `noexcept` means code might throw exceptions. As it has zero effect in this codebase, I am removing to avoid arguments. --- cores/nRF5/Tone.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 2b04688e..7c35f1bc 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -67,13 +67,13 @@ class TONE_PWM_CONFIG { boolean is_initialized; //< defaults to uninitialized public: - bool EnsurePwmPeripheralOwnership(void) noexcept; - bool InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count, uint16_t time_period) noexcept; - bool ApplyConfiguration(uint32_t pin) noexcept; - bool StartPlayback(void) noexcept; - bool StopPlayback(bool releaseOwnership = false) noexcept; - bool ApplyConfigurationAndStartPlayback(uint32_t pin) noexcept; - uint64_t CalculateExpectedPulseCount(void) noexcept; + bool EnsurePwmPeripheralOwnership(void); + bool InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count, uint16_t time_period); + bool ApplyConfiguration(uint32_t pin); + bool StartPlayback(void); + bool StopPlayback(bool releaseOwnership = false); + bool ApplyConfigurationAndStartPlayback(uint32_t pin); + uint64_t CalculateExpectedPulseCount(void); }; TONE_PWM_CONFIG _pwm_config; @@ -116,7 +116,7 @@ constexpr inline static uint64_t _calculate_pulse_count(uint32_t frequency, uint (duration / 1000ULL) * frequency : (((uint64_t)duration) * frequency / 1000ULL); }; -inline static int _bits_used(unsigned long x) noexcept { +inline static int _bits_used(unsigned long x) { if (0 == x) return 0; unsigned int result = 0; do { @@ -124,7 +124,7 @@ inline static int _bits_used(unsigned long x) noexcept { } while (x >>= 1); return result; } -inline static int _bits_used(unsigned long long x) noexcept { +inline static int _bits_used(unsigned long long x) { if (0 == x) return 0; unsigned int result = 0; do { @@ -265,7 +265,7 @@ bool TONE_PWM_CONFIG::EnsurePwmPeripheralOwnership(void) { // COUNT += (start at SEQ0) ? (SEQ0.CNT * (SEQ0.REFRESH+1) : 0; // COUNT += 1; // final SEQ1 emits single pulse // -bool TONE_PWM_CONFIG::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count_x, uint16_t time_period) noexcept { +bool TONE_PWM_CONFIG::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"); @@ -339,7 +339,7 @@ bool TONE_PWM_CONFIG::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count this->is_initialized = true; return true; } -bool TONE_PWM_CONFIG::ApplyConfiguration(uint32_t pin) noexcept { +bool TONE_PWM_CONFIG::ApplyConfiguration(uint32_t pin) { if (!this->is_initialized) { return false; } @@ -394,7 +394,7 @@ bool TONE_PWM_CONFIG::ApplyConfiguration(uint32_t pin) noexcept { nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_LOOPSDONE); return true; } -bool TONE_PWM_CONFIG::StartPlayback(void) noexcept { +bool TONE_PWM_CONFIG::StartPlayback(void) { if (!this->is_initialized) { LOG_LV1("TON", "Cannot start playback without first initializing"); return false; From 4555fc1b0a137b83b2eee77148399793aee5684b Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Tue, 11 Aug 2020 23:00:37 -0700 Subject: [PATCH 40/76] Rename struct per @hathach request --- cores/nRF5/Tone.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 7c35f1bc..bcd1d2da 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -46,7 +46,7 @@ static NRF_PWM_Type * const _PWMInstance = NRF_PWM2; static HardwarePWM * const _HwPWM = HwPWMx[2]; // Defined a struct, to simplify validation testing ... also provides context when debugging -class TONE_PWM_CONFIG { +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; @@ -75,7 +75,7 @@ class TONE_PWM_CONFIG { bool ApplyConfigurationAndStartPlayback(uint32_t pin); uint64_t CalculateExpectedPulseCount(void); }; -TONE_PWM_CONFIG _pwm_config; +TonePwmConfig _pwm_config; inline static bool _is_pwm_enabled(NRF_PWM_Type const * pwm_instance) { bool isEnabled = @@ -227,8 +227,8 @@ void noTone(uint8_t pin) _pwm_config.StopPlayback(true); // release ownership of PWM peripheral } -bool TONE_PWM_CONFIG::EnsurePwmPeripheralOwnership(void) { - if (!_HwPWM->isOwner(TONE_PWM_CONFIG::toneToken) && !_HwPWM->takeOwnership(TONE_PWM_CONFIG::toneToken)) { +bool TonePwmConfig::EnsurePwmPeripheralOwnership(void) { + if (!_HwPWM->isOwner(TonePwmConfig::toneToken) && !_HwPWM->takeOwnership(TonePwmConfig::toneToken)) { LOG_LV1("TON", "unable to allocate PWM2 to Tone"); return false; } @@ -265,7 +265,7 @@ bool TONE_PWM_CONFIG::EnsurePwmPeripheralOwnership(void) { // COUNT += (start at SEQ0) ? (SEQ0.CNT * (SEQ0.REFRESH+1) : 0; // COUNT += 1; // final SEQ1 emits single pulse // -bool TONE_PWM_CONFIG::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count_x, uint16_t time_period) { +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"); @@ -339,7 +339,7 @@ bool TONE_PWM_CONFIG::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count this->is_initialized = true; return true; } -bool TONE_PWM_CONFIG::ApplyConfiguration(uint32_t pin) { +bool TonePwmConfig::ApplyConfiguration(uint32_t pin) { if (!this->is_initialized) { return false; } @@ -363,8 +363,8 @@ bool TONE_PWM_CONFIG::ApplyConfiguration(uint32_t pin) { nrf_pwm_pins_set(_PWMInstance, pins); // must set pins before enabling nrf_pwm_enable(_PWMInstance); - nrf_pwm_configure(_PWMInstance, TONE_PWM_CONFIG::clock_frequency, TONE_PWM_CONFIG::pwm_mode, this->time_period); - nrf_pwm_decoder_set(_PWMInstance, TONE_PWM_CONFIG::load_mode, TONE_PWM_CONFIG::step_mode); + 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_shorts_set(_PWMInstance, this->shorts); nrf_pwm_int_set(_PWMInstance, 0); @@ -394,7 +394,7 @@ bool TONE_PWM_CONFIG::ApplyConfiguration(uint32_t pin) { nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_LOOPSDONE); return true; } -bool TONE_PWM_CONFIG::StartPlayback(void) { +bool TonePwmConfig::StartPlayback(void) { if (!this->is_initialized) { LOG_LV1("TON", "Cannot start playback without first initializing"); return false; @@ -406,11 +406,11 @@ bool TONE_PWM_CONFIG::StartPlayback(void) { nrf_pwm_task_trigger(_PWMInstance, this->task_to_start); return true; } -bool TONE_PWM_CONFIG::StopPlayback(bool releaseOwnership) { +bool TonePwmConfig::StopPlayback(bool releaseOwnership) { bool notInIsr = !isInISR(); - if (!_HwPWM->isOwner(TONE_PWM_CONFIG::toneToken)) { + if (!_HwPWM->isOwner(TonePwmConfig::toneToken)) { if (notInIsr) { LOG_LV2("TON", "Attempt to set noTone when not the owner of the PWM peripheral. Ignoring call...."); } @@ -424,7 +424,7 @@ bool TONE_PWM_CONFIG::StopPlayback(bool releaseOwnership) { } if (releaseOwnership) { - _HwPWM->releaseOwnership(TONE_PWM_CONFIG::toneToken); + _HwPWM->releaseOwnership(TonePwmConfig::toneToken); } return true; } From 1ba129906163a7eb1326806c686d2c4ee3027b31 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Tue, 11 Aug 2020 23:05:08 -0700 Subject: [PATCH 41/76] change casing of class functions per @hathach request --- cores/nRF5/Tone.cpp | 40 +++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index bcd1d2da..b60748ac 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -67,13 +67,11 @@ class TonePwmConfig { boolean is_initialized; //< defaults to uninitialized public: - bool EnsurePwmPeripheralOwnership(void); - bool InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count, uint16_t time_period); - bool ApplyConfiguration(uint32_t pin); - bool StartPlayback(void); - bool StopPlayback(bool releaseOwnership = false); - bool ApplyConfigurationAndStartPlayback(uint32_t pin); - uint64_t CalculateExpectedPulseCount(void); + bool ensurePwmPeripheralOwnership(void); + bool initializeFromPulseCountAndTimePeriod(uint64_t pulse_count, uint16_t time_period); + bool applyConfiguration(uint32_t pin); + bool startPlayback(void); + bool stopPlayback(bool releaseOwnership = false); }; TonePwmConfig _pwm_config; @@ -205,15 +203,15 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) uint64_t pulse_count = _calculate_pulse_count(frequency, duration); uint16_t time_period = _calculate_time_period(frequency); - if (!_pwm_config.EnsurePwmPeripheralOwnership()) { + if (!_pwm_config.ensurePwmPeripheralOwnership()) { LOG_LV1("TON", "Unable to acquire PWM peripheral"); - } else if (!_pwm_config.StopPlayback()) { + } else if (!_pwm_config.stopPlayback()) { LOG_LV1("TON", "Unable to stop playback"); - } else if (!_pwm_config.InitializeFromPulseCountAndTimePeriod(pulse_count, time_period)) { + } else if (!_pwm_config.initializeFromPulseCountAndTimePeriod(pulse_count, time_period)) { LOG_LV1("TON", "Failed calculating configuration"); - } else if (!_pwm_config.ApplyConfiguration(pin)) { + } else if (!_pwm_config.applyConfiguration(pin)) { LOG_LV1("TON", "Failed applying configuration"); - } else if (!_pwm_config.StartPlayback()) { + } else if (!_pwm_config.startPlayback()) { LOG_LV1("TON", "Failed attempting to start PWM peripheral"); } else { //LOG_LV2("TON", "Started playback of tone at frequency %d duration %ld", frequency, duration); @@ -224,10 +222,10 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) void noTone(uint8_t pin) { ( void )pin; // avoid unreferenced parameter compiler warning - _pwm_config.StopPlayback(true); // release ownership of PWM peripheral + _pwm_config.stopPlayback(true); // release ownership of PWM peripheral } -bool TonePwmConfig::EnsurePwmPeripheralOwnership(void) { +bool TonePwmConfig::ensurePwmPeripheralOwnership(void) { if (!_HwPWM->isOwner(TonePwmConfig::toneToken) && !_HwPWM->takeOwnership(TonePwmConfig::toneToken)) { LOG_LV1("TON", "unable to allocate PWM2 to Tone"); return false; @@ -265,7 +263,7 @@ bool TonePwmConfig::EnsurePwmPeripheralOwnership(void) { // COUNT += (start at SEQ0) ? (SEQ0.CNT * (SEQ0.REFRESH+1) : 0; // COUNT += 1; // final SEQ1 emits single pulse // -bool TonePwmConfig::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count_x, uint16_t time_period) { +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"); @@ -339,17 +337,17 @@ bool TonePwmConfig::InitializeFromPulseCountAndTimePeriod(uint64_t pulse_count_x this->is_initialized = true; return true; } -bool TonePwmConfig::ApplyConfiguration(uint32_t pin) { +bool TonePwmConfig::applyConfiguration(uint32_t pin) { if (!this->is_initialized) { return false; } if (pin >= PINS_COUNT) { return false; } - if (!this->EnsurePwmPeripheralOwnership()) { + if (!this->ensurePwmPeripheralOwnership()) { return false; } - this->StopPlayback(false); + this->stopPlayback(false); this->arduino_pin = pin; this->nrf_pin = g_ADigitalPinMap[pin]; @@ -394,19 +392,19 @@ bool TonePwmConfig::ApplyConfiguration(uint32_t pin) { nrf_pwm_event_clear(_PWMInstance, NRF_PWM_EVENT_LOOPSDONE); return true; } -bool TonePwmConfig::StartPlayback(void) { +bool TonePwmConfig::startPlayback(void) { if (!this->is_initialized) { LOG_LV1("TON", "Cannot start playback without first initializing"); return false; } - if (!this->EnsurePwmPeripheralOwnership()) { + if (!this->ensurePwmPeripheralOwnership()) { LOG_LV1("TON", "PWM peripheral not available for playback"); return false; } nrf_pwm_task_trigger(_PWMInstance, this->task_to_start); return true; } -bool TonePwmConfig::StopPlayback(bool releaseOwnership) { +bool TonePwmConfig::stopPlayback(bool releaseOwnership) { bool notInIsr = !isInISR(); From a7ffaaadbd073a4d9f4cb9254fa448dccbc7cc1e Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Tue, 11 Aug 2020 23:35:59 -0700 Subject: [PATCH 42/76] @hathach doesn't like static_assert --- cores/nRF5/Tone.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index b60748ac..5bd1c9dd 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -104,7 +104,6 @@ constexpr inline static uint64_t _calculate_pulse_count(uint32_t frequency, uint // range for frequency == [20..25000], // range for duration == [ 1..0xFFFF_FFFF] // so range of result == [ 1..0x18_FFFF_FFE7] (requires 37 bits) - static_assert(sizeof(unsigned long long) >= sizeof(uint64_t)); return (duration == 0) ? 0 : @@ -174,9 +173,6 @@ inline static int _bits_used(unsigned long long x) { */ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) { - static_assert(sizeof(unsigned long int) <= sizeof(uint32_t)); - static_assert(sizeof(unsigned int) <= sizeof(uint32_t)); - // Used only to protect calls against simultaneous multiple calls to tone(). // Using a function-local static to avoid accidental reference from ISR or elsewhere, // and to simplify ensuring the semaphore gets initialized. From 5f3d871d91d6fed7a359e35fd707ee42c644b9ed Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Tue, 11 Aug 2020 23:42:17 -0700 Subject: [PATCH 43/76] @hathach says internal classes should not guard against API misuse ... I disagree but he is the gatekeeper --- cores/nRF5/Tone.cpp | 9 --------- 1 file changed, 9 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 5bd1c9dd..36e6bdbb 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -64,7 +64,6 @@ class TonePwmConfig { 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 - boolean is_initialized; //< defaults to uninitialized public: bool ensurePwmPeripheralOwnership(void); @@ -330,13 +329,9 @@ bool TonePwmConfig::initializeFromPulseCountAndTimePeriod(uint64_t pulse_count_x this->seq1_refresh = (total_refresh_count - seq0_count) - 1; this->shorts = NRF_PWM_SHORT_LOOPSDONE_STOP_MASK; } - this->is_initialized = true; return true; } bool TonePwmConfig::applyConfiguration(uint32_t pin) { - if (!this->is_initialized) { - return false; - } if (pin >= PINS_COUNT) { return false; } @@ -389,10 +384,6 @@ bool TonePwmConfig::applyConfiguration(uint32_t pin) { return true; } bool TonePwmConfig::startPlayback(void) { - if (!this->is_initialized) { - LOG_LV1("TON", "Cannot start playback without first initializing"); - return false; - } if (!this->ensurePwmPeripheralOwnership()) { LOG_LV1("TON", "PWM peripheral not available for playback"); return false; From 53819e509156299d9d172268dac074abb8ccdda4 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Wed, 12 Aug 2020 10:35:35 -0700 Subject: [PATCH 44/76] More removal of `noexcept` markings --- cores/nRF5/Tone.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 36e6bdbb..c2321d8d 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -93,13 +93,13 @@ inline static bool _is_pwm_enabled(NRF_PWM_Type const * pwm_instance) { See https://gist.github.com/henrygab/6b570ebd51354bf247633c72b8dc383b for code that compares the new lambdas to the old calculations. */ -constexpr inline static uint16_t _calculate_time_period(uint32_t frequency) throw() { +constexpr inline static uint16_t _calculate_time_period(uint32_t frequency) { // range for frequency == [20..25000], // so range of result == [ 5..62500] // which fits in 16 bits. return 125000 / frequency; }; -constexpr inline static uint64_t _calculate_pulse_count(uint32_t frequency, uint32_t duration) throw() { +constexpr inline static uint64_t _calculate_pulse_count(uint32_t frequency, uint32_t duration) { // range for frequency == [20..25000], // range for duration == [ 1..0xFFFF_FFFF] // so range of result == [ 1..0x18_FFFF_FFE7] (requires 37 bits) @@ -176,7 +176,7 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) // Using a function-local static to avoid accidental reference from ISR or elsewhere, // and to simplify ensuring the semaphore gets initialized. static StaticSemaphore_t _tone_semaphore_allocation; - static auto init_semaphore = [] () throw() { //< use a lambda to both initialize AND give the mutex + static auto init_semaphore = [] () { //< use a lambda to both initialize AND give the mutex SemaphoreHandle_t handle = xSemaphoreCreateMutexStatic(&_tone_semaphore_allocation); auto mustSucceed = xSemaphoreGive(handle); (void)mustSucceed; From a5afbec143bf5cf7253a4b75e396ea2dea0aaf97 Mon Sep 17 00:00:00 2001 From: Petr Nejedly Date: Mon, 10 Aug 2020 20:37:35 -0700 Subject: [PATCH 45/76] Nenik: Fix scheduling at the end of delay(), #537 See https://devzone.nordicsemi.com/f/nordic-q-a/63828/vtaskdelay-on-nrf52-freertos-port-wastes-cpu-power for reference --- .../portable/CMSIS/nrf52/port_cmsis_systick.c | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c index 21dec1fc..ec01aa10 100644 --- a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c +++ b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c @@ -227,9 +227,27 @@ void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) diff = xExpectedIdleTime; } - if (diff > 0) + // nRF-provided fix for delay() wakeup 1ms spin-loop power waste + // See https://devzone.nordicsemi.com/f/nordic-q-a/63828/vtaskdelay-on-nrf52-freertos-port-wastes-cpu-power + BaseType_t switch_req = pdFALSE; + + if (diff > 1) { - vTaskStepTick(diff); + vTaskStepTick(diff - 1); + switch_req = xTaskIncrementTick(); + } + else if (diff == 1) + { + switch_req = xTaskIncrementTick(); + } + + /* Increment the RTOS tick as usual which checks if there is a need for rescheduling */ + if ( switch_req != pdFALSE ) + { + /* A context switch is required. Context switching is performed in + the PendSV interrupt. Pend the PendSV interrupt. */ + SCB->ICSR = SCB_ICSR_PENDSVSET_Msk; + __SEV(); } } } From 3ada760cef7af9c5ad11091ec14ef26e5bbcefa4 Mon Sep 17 00:00:00 2001 From: Petr Nejedly Date: Mon, 10 Aug 2020 20:48:02 -0700 Subject: [PATCH 46/76] Nenik: Re-enable SD specific sleep path, related to #165 When the SoftDevice is active (e.g. as soon as you call Bluefruit.begin()), standby by __WFE seems to keep external Xtal oscillator running (at least on nRF52832), increasing the standby power consumption by 500-800uA. The SD-enabled path was apparently disabled mistakenly by Nordic, see Nordic post for reference: https://devzone.nordicsemi.com/f/nordic-q-a/35073/high-power-consumption-of-softdevice/136048#136048 --- cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c index ec01aa10..8cd5967b 100644 --- a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c +++ b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c @@ -182,7 +182,6 @@ void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) configPRE_SLEEP_PROCESSING( xModifiableIdleTime ); if ( xModifiableIdleTime > 0 ) { -#if 0 // With FreeRTOS sd_app_evt_wait increases power consumption with FreeRTOS compared to _WFE (NRFFOSDK-11174) #ifdef SOFTDEVICE_PRESENT // TODO uint8_t sd_en = 0; (void) sd_softdevice_is_enabled(&sd_en); @@ -193,7 +192,6 @@ void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) } else #endif -#endif // (NRFFOSDK-11174) { /* No SD - we would just block interrupts globally. * BASEPRI cannot be used for that because it would prevent WFE from wake up. From 2970c507756b567c484d5f56cc0788dec889fd04 Mon Sep 17 00:00:00 2001 From: Petr Nejedly Date: Mon, 10 Aug 2020 21:29:48 -0700 Subject: [PATCH 47/76] Nenik: Fix FPU-caused power consumption issue, related to #165 Apply the workaround from the Errata 87 of nRF52832 See https://infocenter.nordicsemi.com/topic/errata_nRF52832_Rev2/ERR/nRF52832/Rev2/latest/anomaly_832_87.html?cp=4_2_1_0_1_24 --- .../freertos/portable/CMSIS/nrf52/port_cmsis_systick.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c index 8cd5967b..29dfb57d 100644 --- a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c +++ b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c @@ -182,6 +182,13 @@ void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) configPRE_SLEEP_PROCESSING( xModifiableIdleTime ); if ( xModifiableIdleTime > 0 ) { +#if (__FPU_USED == 1) + // nRF52832 errata 87: prevent FPU from keeping CPU on + // https://infocenter.nordicsemi.com/topic/errata_nRF52832_Rev2/ERR/nRF52832/Rev2/latest/anomaly_832_87.html?cp=4_2_1_0_1_24 + __set_FPSCR(__get_FPSCR() & ~(0x0000009F)); + (void) __get_FPSCR(); + NVIC_ClearPendingIRQ(FPU_IRQn); +#endif #ifdef SOFTDEVICE_PRESENT // TODO uint8_t sd_en = 0; (void) sd_softdevice_is_enabled(&sd_en); From 4c593ed216facbaf0fa8c15932c968c53c8b657f Mon Sep 17 00:00:00 2001 From: Trevor Date: Thu, 13 Aug 2020 19:46:43 -0600 Subject: [PATCH 48/76] Revised Wire library to have I2C setPins updated with hathach requested variable naming and spacing --- libraries/Wire/Wire.h | 2 +- libraries/Wire/Wire_nRF52.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/libraries/Wire/Wire.h b/libraries/Wire/Wire.h index 0c65a00c..a0b2962e 100755 --- a/libraries/Wire/Wire.h +++ b/libraries/Wire/Wire.h @@ -39,7 +39,7 @@ class TwoWire : public Stream void begin(uint8_t); void end(); void setClock(uint32_t); - void setPins(uint8_t pin_SDA, uint8_t pin_SCL); + void setPins(uint8_t pinSDA, uint8_t pinSCL); void beginTransmission(uint8_t); uint8_t endTransmission(bool stopBit); diff --git a/libraries/Wire/Wire_nRF52.cpp b/libraries/Wire/Wire_nRF52.cpp index 81b9564b..427f56c9 100755 --- a/libraries/Wire/Wire_nRF52.cpp +++ b/libraries/Wire/Wire_nRF52.cpp @@ -127,10 +127,10 @@ void TwoWire::setClock(uint32_t baudrate) { } } -void TwoWire::setPins(uint8_t pin_SDA, uint8_t pin_SCL) +void TwoWire::setPins(uint8_t pinSDA, uint8_t pinSCL) { - this->_uc_pinSDA = g_ADigitalPinMap[pin_SDA]; - this->_uc_pinSCL = g_ADigitalPinMap[pin_SCL]; + this->_uc_pinSDA = g_ADigitalPinMap[pinSDA]; + this->_uc_pinSCL = g_ADigitalPinMap[pinSCL]; } void TwoWire::end() { From 304e29d54aea2c96bf5c8518776ec488f816386a Mon Sep 17 00:00:00 2001 From: Trevor Date: Thu, 13 Aug 2020 19:49:14 -0600 Subject: [PATCH 49/76] set pins fixed tab spacing Second try at spacing format for I2C set pins --- libraries/Wire/Wire.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/Wire/Wire.h b/libraries/Wire/Wire.h index a0b2962e..2100c9d2 100755 --- a/libraries/Wire/Wire.h +++ b/libraries/Wire/Wire.h @@ -39,7 +39,7 @@ class TwoWire : public Stream void begin(uint8_t); void end(); void setClock(uint32_t); - void setPins(uint8_t pinSDA, uint8_t pinSCL); + void setPins(uint8_t pinSDA, uint8_t pinSCL); void beginTransmission(uint8_t); uint8_t endTransmission(bool stopBit); From e51b6f48084484558c4cc382774594fb3ad0429d Mon Sep 17 00:00:00 2001 From: Kevin Frei Date: Fri, 14 Aug 2020 09:19:05 -0700 Subject: [PATCH 50/76] Added resumeLoop functionality --- cores/nRF5/Arduino.h | 2 ++ cores/nRF5/main.cpp | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/cores/nRF5/Arduino.h b/cores/nRF5/Arduino.h index 5497dbbd..e8076ff9 100644 --- a/cores/nRF5/Arduino.h +++ b/cores/nRF5/Arduino.h @@ -36,6 +36,8 @@ void setup( void ) ; void loop( void ) ; void suspendLoop(void); +void resumeLoop(void); +void resumeLoopFromISR(void); #include "WVariant.h" diff --git a/cores/nRF5/main.cpp b/cores/nRF5/main.cpp index 62266ac7..89c114a1 100644 --- a/cores/nRF5/main.cpp +++ b/cores/nRF5/main.cpp @@ -100,6 +100,15 @@ void suspendLoop(void) vTaskSuspend(_loopHandle); } +void resumeLoop(void) +{ + vTaskResume(_loopHandle); +} + +void resumeLoopFromISR(void) { + xTaskResumeFromISR(_loopHandle); +} + extern "C" { From 0a656410be0f88a7bd61767923e86348bbdea22e Mon Sep 17 00:00:00 2001 From: Kevin Frei Date: Mon, 17 Aug 2020 09:47:54 -0700 Subject: [PATCH 51/76] No need for the separate ISR routine: just check --- cores/nRF5/main.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/cores/nRF5/main.cpp b/cores/nRF5/main.cpp index 89c114a1..00e6593b 100644 --- a/cores/nRF5/main.cpp +++ b/cores/nRF5/main.cpp @@ -102,11 +102,14 @@ void suspendLoop(void) void resumeLoop(void) { - vTaskResume(_loopHandle); -} - -void resumeLoopFromISR(void) { - xTaskResumeFromISR(_loopHandle); + if ( isInISR() ) + { + xTaskResumeFromISR(_loopHandle); + } + else + { + vTaskResume(_loopHandle); + } } extern "C" From 147c8246accdf8502016af8e9e05269ebc7ae7d2 Mon Sep 17 00:00:00 2001 From: Kevin Frei Date: Mon, 17 Aug 2020 09:54:42 -0700 Subject: [PATCH 52/76] Removed the declaration for the unneeded function. --- cores/nRF5/Arduino.h | 1 - 1 file changed, 1 deletion(-) diff --git a/cores/nRF5/Arduino.h b/cores/nRF5/Arduino.h index e8076ff9..33e2dda7 100644 --- a/cores/nRF5/Arduino.h +++ b/cores/nRF5/Arduino.h @@ -37,7 +37,6 @@ void loop( void ) ; void suspendLoop(void); void resumeLoop(void); -void resumeLoopFromISR(void); #include "WVariant.h" From 9a960037bb56b33f5d7c99baca795622c61c0c7a Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 20 Aug 2020 23:15:40 +0700 Subject: [PATCH 53/76] correct micro ticks --- cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c index 44f90ac1..44ab0155 100644 --- a/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c +++ b/cores/nRF5/freertos/portable/CMSIS/nrf52/port_cmsis_systick.c @@ -243,7 +243,7 @@ void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) // If dwt cycle count is enable, adjust it as welll if ( (CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk) && (DWT->CTRL & DWT_CTRL_CYCCNTENA_Msk) ) { - DWT->CYCCNT += ((diff * 1000000) / configTICK_RATE_HZ) * 64; + DWT->CYCCNT += (((diff-1) * 1000000) / configTICK_RATE_HZ) * 64; } switch_req = xTaskIncrementTick(); From b7fc0a2b3de4d4a1f8de0530bbd6d79e93f62d3a Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Mon, 24 Aug 2020 10:52:32 -0700 Subject: [PATCH 54/76] Remove semaphore from tone() --- cores/nRF5/Tone.cpp | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index c2321d8d..021f9e29 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -172,32 +172,13 @@ inline static int _bits_used(unsigned long long x) { */ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) { - // Used only to protect calls against simultaneous multiple calls to tone(). - // Using a function-local static to avoid accidental reference from ISR or elsewhere, - // and to simplify ensuring the semaphore gets initialized. - static StaticSemaphore_t _tone_semaphore_allocation; - static auto init_semaphore = [] () { //< use a lambda to both initialize AND give the mutex - SemaphoreHandle_t handle = xSemaphoreCreateMutexStatic(&_tone_semaphore_allocation); - auto mustSucceed = xSemaphoreGive(handle); - (void)mustSucceed; - NRFX_ASSERT(mustSucceed == pdTRUE); - return handle; - }; - static SemaphoreHandle_t _tone_semaphore = init_semaphore(); - // limit frequency to reasonable audible range if((frequency < 20) | (frequency > 25000)) { LOG_LV1("TON", "frequency outside range [20..25000] -- ignoring"); return; } - - if(xSemaphoreTake(_tone_semaphore, portMAX_DELAY) != pdTRUE) { - LOG_LV1("TON", "error acquiring semaphore (should never occur?)"); - 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"); } else if (!_pwm_config.stopPlayback()) { @@ -211,7 +192,6 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) } else { //LOG_LV2("TON", "Started playback of tone at frequency %d duration %ld", frequency, duration); } - xSemaphoreGive(_tone_semaphore); return; } void noTone(uint8_t pin) From 1097f1a5832189b478eb491cb8dbafd889fd697a Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Mon, 24 Aug 2020 10:55:41 -0700 Subject: [PATCH 55/76] inline != __attribute__((always_inline)) --- cores/nRF5/Tone.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 021f9e29..2ffd61ac 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -74,7 +74,7 @@ class TonePwmConfig { }; TonePwmConfig _pwm_config; -inline static bool _is_pwm_enabled(NRF_PWM_Type const * pwm_instance) { +static bool _is_pwm_enabled(NRF_PWM_Type const * pwm_instance) { bool isEnabled = (pwm_instance->ENABLE & PWM_ENABLE_ENABLE_Msk) == (PWM_ENABLE_ENABLE_Enabled << PWM_ENABLE_ENABLE_Pos); @@ -93,13 +93,13 @@ inline static bool _is_pwm_enabled(NRF_PWM_Type const * pwm_instance) { See https://gist.github.com/henrygab/6b570ebd51354bf247633c72b8dc383b for code that compares the new lambdas to the old calculations. */ -constexpr inline static uint16_t _calculate_time_period(uint32_t frequency) { +constexpr static uint16_t _calculate_time_period(uint32_t frequency) { // range for frequency == [20..25000], // so range of result == [ 5..62500] // which fits in 16 bits. return 125000 / frequency; }; -constexpr inline static uint64_t _calculate_pulse_count(uint32_t frequency, uint32_t duration) { +constexpr static uint64_t _calculate_pulse_count(uint32_t frequency, uint32_t duration) { // range for frequency == [20..25000], // range for duration == [ 1..0xFFFF_FFFF] // so range of result == [ 1..0x18_FFFF_FFE7] (requires 37 bits) @@ -112,7 +112,7 @@ constexpr inline static uint64_t _calculate_pulse_count(uint32_t frequency, uint (duration / 1000ULL) * frequency : (((uint64_t)duration) * frequency / 1000ULL); }; -inline static int _bits_used(unsigned long x) { +static int _bits_used(unsigned long x) { if (0 == x) return 0; unsigned int result = 0; do { @@ -120,7 +120,7 @@ inline static int _bits_used(unsigned long x) { } while (x >>= 1); return result; } -inline static int _bits_used(unsigned long long x) { +static int _bits_used(unsigned long long x) { if (0 == x) return 0; unsigned int result = 0; do { From cda1dba5403d0214368e1d6a3a7c9feaa8423abd Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Mon, 24 Aug 2020 11:26:50 -0700 Subject: [PATCH 56/76] More constexpr --- cores/nRF5/Tone.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 2ffd61ac..3ebe950f 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -64,7 +64,6 @@ class TonePwmConfig { 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); @@ -112,7 +111,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) { +constexpr static int _bits_used(unsigned long x) { if (0 == x) return 0; unsigned int result = 0; do { @@ -120,7 +119,7 @@ static int _bits_used(unsigned long x) { } while (x >>= 1); return result; } -static int _bits_used(unsigned long long x) { +constexpr static int _bits_used(unsigned long long x) { if (0 == x) return 0; unsigned int result = 0; do { From eb60126903245deebba1acdade2618619a8dde22 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Mon, 24 Aug 2020 13:13:25 -0700 Subject: [PATCH 57/76] not constexpr enough for C++14? --- cores/nRF5/Tone.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 3ebe950f..27a8a88a 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -111,7 +111,7 @@ constexpr static uint64_t _calculate_pulse_count(uint32_t frequency, uint32_t du (duration / 1000ULL) * frequency : (((uint64_t)duration) * frequency / 1000ULL); }; -constexpr static int _bits_used(unsigned long x) { +static int _bits_used(unsigned long x) { if (0 == x) return 0; unsigned int result = 0; do { @@ -119,7 +119,7 @@ constexpr static int _bits_used(unsigned long x) { } while (x >>= 1); return result; } -constexpr static int _bits_used(unsigned long long x) { +static int _bits_used(unsigned long long x) { if (0 == x) return 0; unsigned int result = 0; do { From 947d8bb6f7f8f5dbf25d8c4bfc2b1e6997c2e3da Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 25 Aug 2020 10:06:43 +0700 Subject: [PATCH 58/76] 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 59/76] 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 60/76] 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 61/76] 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 62/76] 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 63/76] 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 64/76] 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 65/76] 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 66/76] 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 132f11de33d57d1536bc2a296d6febfaad586d4e Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 12:18:23 +0700 Subject: [PATCH 67/76] rename I2C terminology --- libraries/Wire/Wire_nRF52.cpp | 4 ++-- .../examples/SFRRanger_reader/SFRRanger_reader.ino | 4 ++-- .../digital_potentiometer/digital_potentiometer.ino | 2 +- .../main_reader.ino} | 12 ++++++------ .../master_scan.ino => main_scan/main_scan.ino} | 0 .../main_writer.ino} | 8 ++++---- .../secondary_receiver.ino} | 8 ++++---- .../secondary_sender.ino} | 10 +++++----- 8 files changed, 24 insertions(+), 24 deletions(-) rename libraries/Wire/examples/{master_reader/master_reader.ino => main_reader/main_reader.ino} (57%) rename libraries/Wire/examples/{master_scan/master_scan.ino => main_scan/main_scan.ino} (100%) rename libraries/Wire/examples/{master_writer/master_writer.ino => main_writer/main_writer.ino} (70%) rename libraries/Wire/examples/{slave_receiver/slave_receiver.ino => secondary_receiver/secondary_receiver.ino} (81%) rename libraries/Wire/examples/{slave_sender/slave_sender.ino => secondary_sender/secondary_sender.ino} (67%) diff --git a/libraries/Wire/Wire_nRF52.cpp b/libraries/Wire/Wire_nRF52.cpp index 427f56c9..3875039e 100755 --- a/libraries/Wire/Wire_nRF52.cpp +++ b/libraries/Wire/Wire_nRF52.cpp @@ -46,7 +46,7 @@ TwoWire::TwoWire(NRF_TWIM_Type * p_twim, NRF_TWIS_Type * p_twis, IRQn_Type IRQn, } void TwoWire::begin(void) { - //Master Mode + //Main Mode master = true; *pincfg_reg(_uc_pinSCL) = ((uint32_t)GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos) @@ -72,7 +72,7 @@ void TwoWire::begin(void) { } void TwoWire::begin(uint8_t address) { - //Slave mode + //Secondary mode master = false; *pincfg_reg(_uc_pinSCL) = ((uint32_t)GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos) diff --git a/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.ino b/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.ino index f41511c1..67007804 100755 --- a/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.ino +++ b/libraries/Wire/examples/SFRRanger_reader/SFRRanger_reader.ino @@ -14,7 +14,7 @@ void setup() { - Wire.begin(); // join i2c bus (address optional for master) + Wire.begin(); // join i2c bus (address optional for main) Serial.begin(9600); // start serial communication at 9600bps while ( !Serial ) delay(10); // for nrf52840 with native usb } @@ -42,7 +42,7 @@ void loop() Wire.endTransmission(); // stop transmitting // step 4: request reading from sensor - Wire.requestFrom(112, 2); // request 2 bytes from slave device #112 + Wire.requestFrom(112, 2); // request 2 bytes from secondary device #112 // step 5: receive reading from sensor if(2 <= Wire.available()) // if two bytes were received diff --git a/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.ino b/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.ino index 38da1c54..54909907 100755 --- a/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.ino +++ b/libraries/Wire/examples/digital_potentiometer/digital_potentiometer.ino @@ -16,7 +16,7 @@ void setup() { - Wire.begin(); // join i2c bus (address optional for master) + Wire.begin(); // join i2c bus (address optional for main) } byte val = 0; diff --git a/libraries/Wire/examples/master_reader/master_reader.ino b/libraries/Wire/examples/main_reader/main_reader.ino similarity index 57% rename from libraries/Wire/examples/master_reader/master_reader.ino rename to libraries/Wire/examples/main_reader/main_reader.ino index ee59610e..7927fab4 100755 --- a/libraries/Wire/examples/master_reader/master_reader.ino +++ b/libraries/Wire/examples/main_reader/main_reader.ino @@ -1,9 +1,9 @@ -// Wire Master Reader +// Wire Main Reader // by Nicholas Zambetti // Demonstrates use of the Wire library -// Reads data from an I2C/TWI slave device -// Refer to the "Wire Slave Sender" example for use with this +// Reads data from an I2C/TWI secondary device +// Refer to the "Wire Secondary Sender" example for use with this // Created 29 March 2006 @@ -14,16 +14,16 @@ void setup() { - Wire.begin(); // join i2c bus (address optional for master) + Wire.begin(); // join i2c bus (address optional for main) Serial.begin(9600); // start serial for output while ( !Serial ) delay(10); // for nrf52840 with native usb } void loop() { - Wire.requestFrom(2, 6); // request 6 bytes from slave device #2 + Wire.requestFrom(2, 6); // request 6 bytes from secondary device #2 - while(Wire.available()) // slave may send less than requested + while(Wire.available()) // secondary may send less than requested { char c = Wire.read(); // receive a byte as character Serial.print(c); // print the character diff --git a/libraries/Wire/examples/master_scan/master_scan.ino b/libraries/Wire/examples/main_scan/main_scan.ino similarity index 100% rename from libraries/Wire/examples/master_scan/master_scan.ino rename to libraries/Wire/examples/main_scan/main_scan.ino diff --git a/libraries/Wire/examples/master_writer/master_writer.ino b/libraries/Wire/examples/main_writer/main_writer.ino similarity index 70% rename from libraries/Wire/examples/master_writer/master_writer.ino rename to libraries/Wire/examples/main_writer/main_writer.ino index ccaa0361..988a3089 100755 --- a/libraries/Wire/examples/master_writer/master_writer.ino +++ b/libraries/Wire/examples/main_writer/main_writer.ino @@ -1,9 +1,9 @@ -// Wire Master Writer +// Wire Main Writer // by Nicholas Zambetti // Demonstrates use of the Wire library -// Writes data to an I2C/TWI slave device -// Refer to the "Wire Slave Receiver" example for use with this +// Writes data to an I2C/TWI secondary device +// Refer to the "Wire Secondary Receiver" example for use with this // Created 29 March 2006 @@ -14,7 +14,7 @@ void setup() { - Wire.begin(); // join i2c bus (address optional for master) + Wire.begin(); // join i2c bus (address optional for main) } byte x = 0; diff --git a/libraries/Wire/examples/slave_receiver/slave_receiver.ino b/libraries/Wire/examples/secondary_receiver/secondary_receiver.ino similarity index 81% rename from libraries/Wire/examples/slave_receiver/slave_receiver.ino rename to libraries/Wire/examples/secondary_receiver/secondary_receiver.ino index c0c26286..77e9590c 100755 --- a/libraries/Wire/examples/slave_receiver/slave_receiver.ino +++ b/libraries/Wire/examples/secondary_receiver/secondary_receiver.ino @@ -1,9 +1,9 @@ -// Wire Slave Receiver +// Wire Secondary Receiver // by Nicholas Zambetti // Demonstrates use of the Wire library -// Receives data as an I2C/TWI slave device -// Refer to the "Wire Master Writer" example for use with this +// Receives data as an I2C/TWI secondary device +// Refer to the "Wire Main Writer" example for use with this // Created 29 March 2006 @@ -25,7 +25,7 @@ void loop() delay(100); } -// function that executes whenever data is received from master +// function that executes whenever data is received from main // this function is registered as an event, see setup() void receiveEvent(int howMany) { diff --git a/libraries/Wire/examples/slave_sender/slave_sender.ino b/libraries/Wire/examples/secondary_sender/secondary_sender.ino similarity index 67% rename from libraries/Wire/examples/slave_sender/slave_sender.ino rename to libraries/Wire/examples/secondary_sender/secondary_sender.ino index d3b238af..974ea45d 100755 --- a/libraries/Wire/examples/slave_sender/slave_sender.ino +++ b/libraries/Wire/examples/secondary_sender/secondary_sender.ino @@ -1,9 +1,9 @@ -// Wire Slave Sender +// Wire Secondary Sender // by Nicholas Zambetti // Demonstrates use of the Wire library -// Sends data as an I2C/TWI slave device -// Refer to the "Wire Master Reader" example for use with this +// Sends data as an I2C/TWI secondary device +// Refer to the "Wire Main Reader" example for use with this // Created 29 March 2006 @@ -23,10 +23,10 @@ void loop() delay(100); } -// function that executes whenever data is requested by master +// function that executes whenever data is requested by main // this function is registered as an event, see setup() void requestEvent() { Wire.write("hello "); // respond with message of 6 bytes - // as expected by master + // as expected by main } From 8577afafc9257925236c45f4d3bef152868cba2b Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 13:15:17 +0700 Subject: [PATCH 68/76] support precompiled library with compiler.libraries.ldflags --- platform.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/platform.txt b/platform.txt index ce3cd4b9..1e6ea7c1 100644 --- a/platform.txt +++ b/platform.txt @@ -74,6 +74,7 @@ compiler.c.elf.extra_flags= compiler.cpp.extra_flags= compiler.S.extra_flags= compiler.ar.extra_flags= +compiler.libraries.ldflags= compiler.elf2bin.extra_flags= compiler.elf2hex.extra_flags= @@ -94,7 +95,7 @@ recipe.S.o.pattern="{compiler.path}{compiler.S.cmd}" {compiler.S.flags} -DF_CPU= recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{archive_file_path}" "{object_file}" ## Combine gc-sections, archives, and objects -recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" "-L{build.path}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} "-L{build.core.path}/linker" "-T{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.ldflags} -o "{build.path}/{build.project_name}.elf" {object_files} -Wl,--start-group -lm "{build.path}/{archive_file}" -Wl,--end-group +recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" "-L{build.path}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} "-L{build.core.path}/linker" "-T{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.ldflags} -o "{build.path}/{build.project_name}.elf" {object_files} {compiler.libraries.ldflags} -Wl,--start-group -lm "{build.path}/{archive_file}" -Wl,--end-group ## Create output (bin file) #recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2bin.cmd}" {compiler.elf2bin.flags} {compiler.elf2bin.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin" From 27c462a4d105091627d94109966f1f5d99e81e1c Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 13:19:13 +0700 Subject: [PATCH 69/76] clean up --- libraries/Wire/examples/main_scan/main_scan.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/Wire/examples/main_scan/main_scan.ino b/libraries/Wire/examples/main_scan/main_scan.ino index 1567477d..37c37f15 100644 --- a/libraries/Wire/examples/main_scan/main_scan.ino +++ b/libraries/Wire/examples/main_scan/main_scan.ino @@ -7,7 +7,7 @@ void setup() { Serial.begin(115200); // start serial for output while ( !Serial ) delay(10); // for nrf52840 with native usb - wi->begin(); // join i2c bus (address optional for master) + wi->begin(); // join i2c bus (address optional for main) } void loop() From b84e2a81f9c75bb221260c3ddc42a3c50b860a71 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 15:15:21 +0700 Subject: [PATCH 70/76] clean up ci build script --- tools/build_all.py | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/tools/build_all.py b/tools/build_all.py index b9f99262..2b2ec52e 100644 --- a/tools/build_all.py +++ b/tools/build_all.py @@ -2,19 +2,24 @@ import os import glob import sys import subprocess +from subprocess import Popen, PIPE import time +SUCCEEDED = "\033[32msucceeded\033[0m" +FAILED = "\033[31mfailed\033[0m" +SKIPPED = "\033[33mskipped\033[0m" +WARNING = "\033[31mwarnings\033[0m" + all_warnings = False exit_status = 0 success_count = 0 fail_count = 0 skip_count = 0 -build_format = '| {:20} | {:35} | {:9} | {:6} |' +build_format = '| {:20} | {:35} | {:18} | {:6} |' build_separator = '-' * 83 default_boards = [ 'cluenrf52840', 'cplaynrf52840', 'feather52832', 'feather52840', 'feather52840sense', 'itsybitsy52840' ] - build_boards = [] # build all variants if input not existed @@ -23,6 +28,9 @@ if len(sys.argv) > 1: else: build_boards = default_boards +all_examples = list(glob.iglob('libraries/**/*.ino', recursive=True)) +all_examples.sort() + def errorOutputFilter(line): if len(line) == 0: return False @@ -39,29 +47,29 @@ def build_examples(variant): print(build_separator) print('| {:^79} |'.format('Board ' + variant)) print(build_separator) - print(build_format.format('Library', 'Example', 'Result', 'Time')) + print(build_format.format('Library', 'Example', '\033[39mResult\033[0m', 'Time')) print(build_separator) fqbn = "adafruit:nrf52:{}:softdevice={},debug=l0".format(variant, 's140v6' if variant != 'feather52832' else 's132v6') - for sketch in glob.iglob('libraries/**/*.ino', recursive=True): + for sketch in all_examples: start_time = time.monotonic() # Skip if contains: ".board.test.skip" or ".all.test.skip" # Skip if not contains: ".board.test.only" for a specific board sketchdir = os.path.dirname(sketch) if os.path.exists(sketchdir + '/.all.test.skip') or os.path.exists(sketchdir + '/.' + variant + '.test.skip'): - success = "\033[33mskipped\033[0m " + success = SKIPPED elif glob.glob(sketchdir+"/.*.test.only") and not os.path.exists(sketchdir + '/.' + variant + '.test.only'): - success = "\033[33mskipped\033[0m " + success = SKIPPED else: # TODO - preferably, would have STDERR show up in **both** STDOUT and STDERR. # preferably, would use Python logging handler to get both distinct outputs and one merged output # for now, split STDERR when building with all warnings enabled, so can detect warning/error output. if all_warnings: - build_result = subprocess.run("arduino-cli compile --warnings all --fqbn {} {}".format(fqbn, sketch), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + build_result = subprocess.run("arduino-cli compile --warnings all --fqbn {} {}".format(fqbn, sketch), shell=True, stdout=PIPE, stderr=PIPE) else: - build_result = subprocess.run("arduino-cli compile --warnings default --fqbn {} {}".format(fqbn, sketch), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + build_result = subprocess.run("arduino-cli compile --warnings default --fqbn {} {}".format(fqbn, sketch), shell=True, stdout=PIPE, stderr=PIPE) # get stderr into a form where len(warningLines) indicates a true warning was output to stderr warningLines = []; @@ -71,21 +79,21 @@ def build_examples(variant): if build_result.returncode != 0: exit_status = build_result.returncode - success = "\033[31mfailed\033[0m " + success = FAILED fail_count += 1 elif len(warningLines) != 0: exit_status = -1 - success = "\033[31mwarnings\033[0m " + success = WARNING fail_count += 1 else: - success = "\033[32msucceeded\033[0m" + success = SUCCEEDED success_count += 1 build_duration = time.monotonic() - start_time print(build_format.format(sketch.split(os.path.sep)[1], os.path.basename(sketch), success, '{:5.2f}s'.format(build_duration))) - if success != "\033[33mskipped\033[0m ": + if success != SKIPPED: if build_result.returncode != 0: print(build_result.stdout.decode("utf-8")) if (build_result.stderr): @@ -96,7 +104,6 @@ def build_examples(variant): else: skip_count += 1 - build_time = time.monotonic() for board in build_boards: @@ -104,7 +111,7 @@ for board in build_boards: print(build_separator) build_time = time.monotonic() - build_time -print("Build Summary: {} \033[32msucceeded\033[0m, {} \033[31mfailed\033[0m, {} \033[33mskipped\033[0m and took {:.2f}s".format(success_count, fail_count, skip_count, build_time)) +print("Build Summary: {} {}, {} {}, {} {} and took {:.2f}s".format(success_count, SUCCEEDED, fail_count, FAILED, skip_count, SKIPPED, build_time)) print(build_separator) sys.exit(exit_status) From 3cc5b5ba73de382e622d55acc650b040223d2767 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 27 Aug 2020 15:28:38 +0700 Subject: [PATCH 71/76] 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 72/76] 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 73/76] 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 74/76] 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 75/76] 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 } From ce81b830a13a28f0e80e31721911a0ea63fc1edf Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 31 Aug 2020 16:49:09 +0700 Subject: [PATCH 76/76] ready for release 0.21.0 --- changelog.md | 23 +++++++- cores/nRF5/HardwarePWM.cpp | 58 ++++++++---------- cores/nRF5/Tone.cpp | 2 + cores/nRF5/wiring_analog.cpp | 59 ++++++++----------- .../tone_happy_birthday.ino | 2 +- libraries/Bluefruit52Lib/library.properties | 2 +- libraries/Servo/src/nrf52/Servo.cpp | 3 + platform.txt | 2 +- 8 files changed, 77 insertions(+), 74 deletions(-) diff --git a/changelog.md b/changelog.md index e4fcfef1..56d8a6c1 100644 --- a/changelog.md +++ b/changelog.md @@ -1,7 +1,28 @@ # Adafruit nRF52 Arduino Core Changelog +## 0.21.0 - 2020.08.31 + +Special thanks to @henrygab, @pyro9, @Nenik, @orrmany, @thaanstad, @kevinfrei for contributing and helping with this release. + +- Reworked HardwarePWM, analogWrite, Servo, Tone to address PWM hardware conflict with ownership. +- Reworked Tone to use no interrupt handler +- Added multiprotocol support such as ANT with additional ANT_LICENSE_KEY (require 3rd party library) +- Fixed pgm_read_ptr(addr) macro +- Updated & enhanced TinyUSB performance, usb event, task switching is much faster +- Fixed BLE Characteristic discovery when the central device returns more than 4 Characteristics in a discovery request +- Enhanced micro() to use DWT cyclecount if enabled for higher precision +- Fixed miscalculated tick when sleeping with delay() +- Fixed FPU-caused power consumption issue +- Added Wire.setPins() +- Added resumeLoop() +- Renamed I2C terminology +- Support precompiled library with compiler.libraries.ldflags e.g BSEC BME680 +- Added Hardware/tone_happy_birthday example sketch + ## 0.20.5 - 2020.07.05 +Special thanks to @henrygab, @pyro9, @geeksville for contributing and helping with this release. + - Updated toolchain from gcc 7-2017q4 to 9-2019q4 - Fixed GPIOTE channel conflict between libraries - Added type-safe for arrcount() macros @@ -9,8 +30,6 @@ - Update CMSIS from v4 to v5 to build with TensorFlow - Update TinyUSB core to commit 0749077 -Special thanks to @henrygab, @pyro9, @geeksville for contributing and helping with this release. - ## 0.20.1 - 2020.04.23 - Update TinyUSB to commit c59fa77 due to a bug in the stack diff --git a/cores/nRF5/HardwarePWM.cpp b/cores/nRF5/HardwarePWM.cpp index 17768ad0..441c3fcb 100644 --- a/cores/nRF5/HardwarePWM.cpp +++ b/cores/nRF5/HardwarePWM.cpp @@ -1,38 +1,28 @@ -/**************************************************************************/ -/*! - @file HardwarePWM.cpp - @author hathach (tinyusb.org) +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Ha Thach for Adafruit Industries + * Copyright (c) 2020 Henry Gabryjelski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2018, Adafruit Industries (adafruit.com) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ #include "Arduino.h" #include "HardwarePWM.h" diff --git a/cores/nRF5/Tone.cpp b/cores/nRF5/Tone.cpp index 9a15fb0f..4f52d31f 100644 --- a/cores/nRF5/Tone.cpp +++ b/cores/nRF5/Tone.cpp @@ -32,6 +32,8 @@ Version Modified By Date Comments 0008 S Kanemoto 12/06/22 Fixed for Leonardo by @maris_HY 0009 Arduino.org 15/06/30 Add M0/M0 Pro support 0010 Arduino.org 16/07/27 Added Arduino Primo support +0011 Henry Gabryjelski 20/08/25 Rework/Rewrite the library to use no interrupt handler and + support HwPWM ownership *************************************************/ #include "Arduino.h" diff --git a/cores/nRF5/wiring_analog.cpp b/cores/nRF5/wiring_analog.cpp index 38fefdf1..79131a7e 100644 --- a/cores/nRF5/wiring_analog.cpp +++ b/cores/nRF5/wiring_analog.cpp @@ -1,38 +1,27 @@ -/**************************************************************************/ -/*! - @file wiring_analog.cpp - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2018, Adafruit Industries (adafruit.com) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020 Ha Thach for Adafruit Industries + * Copyright (c) 2020 Henry Gabryjelski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ #include "Arduino.h" 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 index db4656e3..7500d1c7 100644 --- a/libraries/Bluefruit52Lib/examples/Hardware/tone_happy_birthday/tone_happy_birthday.ino +++ b/libraries/Bluefruit52Lib/examples/Hardware/tone_happy_birthday/tone_happy_birthday.ino @@ -19,7 +19,7 @@ // 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 +#define PIN_BUZZER A0 #endif diff --git a/libraries/Bluefruit52Lib/library.properties b/libraries/Bluefruit52Lib/library.properties index bace4631..abdaacd4 100644 --- a/libraries/Bluefruit52Lib/library.properties +++ b/libraries/Bluefruit52Lib/library.properties @@ -1,5 +1,5 @@ name=Adafruit Bluefruit nRF52 Libraries -version=0.20.5 +version=0.21.0 author=Adafruit maintainer=Adafruit sentence=Arduino library for nRF52-based Adafruit Bluefruit LE modules diff --git a/libraries/Servo/src/nrf52/Servo.cpp b/libraries/Servo/src/nrf52/Servo.cpp index e83b97cb..4103c43f 100644 --- a/libraries/Servo/src/nrf52/Servo.cpp +++ b/libraries/Servo/src/nrf52/Servo.cpp @@ -14,6 +14,9 @@ You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Modified by Ha Thach for Adafruit Industries + Modified by Henry Gabryjelski to add ownershp support */ #if defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT) diff --git a/platform.txt b/platform.txt index 1e6ea7c1..a5a457e6 100644 --- a/platform.txt +++ b/platform.txt @@ -17,7 +17,7 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA name=Adafruit nRF52 Boards -version=0.20.5 +version=0.21.0 # Compile variables # -----------------