Skip to content

Commit 6d1181e

Browse files
committed
PWM_RESOLUTION hardening
Following Arduino API, analogWriteResolution range is: 0 < x <= 32 Signed-off-by: Frederic Pillon <[email protected]>
1 parent bcd341d commit 6d1181e

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

cores/arduino/pins_arduino.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,10 @@ PinName analogInputToPinName(uint32_t pin);
315315
#ifndef PWM_RESOLUTION
316316
#define PWM_RESOLUTION 8
317317
#endif
318+
319+
_Static_assert((PWM_RESOLUTION > 0) &&(PWM_RESOLUTION <= 32),
320+
"PWM_RESOLUTION must be 0 < x <= 32!");
321+
318322
#ifndef PWM_FREQUENCY
319323
#define PWM_FREQUENCY 1000
320324
#endif

cores/arduino/wiring_analog.c

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ extern "C" {
2929
uint32_t g_anOutputPinConfigured[MAX_NB_PORT] = {0};
3030
#endif
3131

32+
#define MAX_PWM_RESOLUTION 16
33+
3234
static int _readResolution = 10;
3335
int _writeResolution = PWM_RESOLUTION;
3436
static uint32_t _writeFreq = PWM_FREQUENCY;
@@ -40,7 +42,11 @@ void analogReadResolution(int res)
4042

4143
void analogWriteResolution(int res)
4244
{
43-
_writeResolution = res;
45+
if ((res > 0) && (res <= 32)) {
46+
_writeResolution = res;
47+
} else {
48+
Error_Handler();
49+
}
4450
}
4551

4652
void analogWriteFrequency(uint32_t freq)
@@ -112,10 +118,15 @@ void analogWrite(uint32_t ulPin, uint32_t ulValue)
112118
#endif //HAL_DAC_MODULE_ENABLED && !HAL_DAC_MODULE_ONLY
113119
#if defined(HAL_TIM_MODULE_ENABLED) && !defined(HAL_TIM_MODULE_ONLY)
114120
if (pin_in_pinmap(p, PinMap_PWM)) {
121+
int internalResolution = _writeResolution;
115122
if (is_pin_configured(p, g_anOutputPinConfigured) == false) {
116123
set_pin_configured(p, g_anOutputPinConfigured);
117124
}
118-
pwm_start(p, _writeFreq, ulValue, _writeResolution);
125+
if (_writeResolution > MAX_PWM_RESOLUTION) {
126+
internalResolution = MAX_PWM_RESOLUTION;
127+
ulValue = mapResolution(ulValue, _writeResolution, internalResolution);
128+
}
129+
pwm_start(p, _writeFreq, ulValue, internalResolution);
119130
} else
120131
#endif /* HAL_TIM_MODULE_ENABLED && !HAL_TIM_MODULE_ONLY */
121132
{

0 commit comments

Comments
 (0)