From af680357dd68eeb9da44d7da9e40febd485df454 Mon Sep 17 00:00:00 2001 From: Henry Gabryjelski Date: Sun, 12 Apr 2020 17:24:23 -0700 Subject: [PATCH] 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"