Skip to content

Commit b9ce5ac

Browse files
soburigbr1facchinm
committed
cores: arduino: analogWrite: Fix max value calculation
- Fixed input max value calculation (Needs to be -1 after shift) - Clamp calculations are performed first, eliminating cast - make internal arduino_adc array static Co-Authored-by: Giovanni Bruno <g.bruno@arduino.cc> Co-Authored-by: Martino Facchin <m.facchin@arduino.cc> Signed-off-by: TOKITA Hiroshi <tokita.hiroshi@gmail.com>
1 parent 6885448 commit b9ce5ac

1 file changed

Lines changed: 12 additions & 8 deletions

File tree

cores/arduino/zephyrCommon.cpp

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -154,14 +154,14 @@ size_t pwm_pin_index(pin_size_t pinNumber) {
154154
DT_PHA_BY_IDX(DT_PATH(zephyr_user), p, i, pin)),
155155
#define ADC_CH_CFG(n, p, i) arduino_adc[i].channel_cfg,
156156

157-
const struct adc_dt_spec arduino_adc[] = {
157+
static const struct adc_dt_spec arduino_adc[] = {
158158
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), io_channels, ADC_DT_SPEC)};
159159

160160
/* io-channel-pins node provides a mapping digital pin numbers to adc channels */
161161
const pin_size_t arduino_analog_pins[] = {
162162
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), adc_pin_gpios, ADC_PINS)};
163163

164-
struct adc_channel_cfg channel_cfg[ARRAY_SIZE(arduino_analog_pins)] = {
164+
struct adc_channel_cfg channel_cfg[] = {
165165
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), io_channels, ADC_CH_CFG)};
166166

167167
size_t analog_pin_index(pin_size_t pinNumber) {
@@ -352,7 +352,13 @@ unsigned long millis(void) {
352352

353353
#ifdef CONFIG_PWM
354354

355+
static uint32_t map64(uint32_t x, uint32_t in_min, uint32_t in_max, uint32_t out_min,
356+
uint32_t out_max) {
357+
return ((uint64_t)(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min);
358+
}
359+
355360
void analogWrite(pin_size_t pinNumber, int value) {
361+
const int maxInput = BIT(_analog_write_resolution) - 1U;
356362
size_t idx = pwm_pin_index(pinNumber);
357363

358364
if (idx >= ARRAY_SIZE(arduino_pwm)) {
@@ -363,17 +369,15 @@ void analogWrite(pin_size_t pinNumber, int value) {
363369
return;
364370
}
365371

366-
if (((uint32_t)value) > arduino_pwm[idx].period) {
367-
value = arduino_pwm[idx].period;
368-
} else if (value < 0) {
369-
value = 0;
370-
}
372+
value = CLAMP(value, 0, maxInput);
373+
374+
const uint32_t pulse = map64(value, 0, maxInput, 0, arduino_pwm[idx].period);
371375

372376
/*
373377
* A duty ratio determines by the period value defined in dts
374378
* and the value arguments. So usually the period value sets as 255.
375379
*/
376-
(void)pwm_set_pulse_dt(&arduino_pwm[idx], value);
380+
(void)pwm_set_pulse_dt(&arduino_pwm[idx], pulse);
377381
}
378382

379383
#endif

0 commit comments

Comments
 (0)