analogWrite() avoids hostile takeover of PWM peripherals

This commit is contained in:
Henry Gabryjelski committed 2020-07-28 23:05:09 -07:00
1 parent b4d777f7f3
commit af680357dd
1 file changed
+58 -8
+58 -8
View File
@@ -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; i<HWPWM_MODULE_NUM; i++)
{
if (!_AnalogState._moduleUsedByAnalogWrites[i]) continue;
HwPWMx[i]->setResolution(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; i<HWPWM_MODULE_NUM; i++)
{
// Added by if needed
if ( HwPWMx[i]->addPin(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; i<HWPWM_MODULE_NUM; i++)
{
if (!_AnalogState._moduleUsedByAnalogWrites[i]) continue;
if (!HwPWMx[i]->addPin(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; i<HWPWM_MODULE_NUM; i++)
{
if (_AnalogState._moduleUsedByAnalogWrites[i]) continue;
if (HwPWMx[i]->usedChannelCount() != 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"