Skip to content

Commit a97f723

Browse files
soburiCopilot
andcommitted
Update cores/arduino/zephyrCommon.cpp
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
1 parent 80a0bd6 commit a97f723

1 file changed

Lines changed: 25 additions & 9 deletions

File tree

cores/arduino/zephyrCommon.cpp

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,7 @@ int analogWriteResolution() {
391391
#ifdef CONFIG_PWM
392392

393393
void analogWrite(pin_size_t pinNumber, int value) {
394+
const int maxInput = (1 << _analog_write_resolution) - 1;
394395
size_t idx = pwm_pin_index(pinNumber);
395396

396397
if (idx >= ARRAY_SIZE(arduino_pwm)) {
@@ -401,34 +402,49 @@ void analogWrite(pin_size_t pinNumber, int value) {
401402
return;
402403
}
403404

404-
value = map(value, 0, 1 << _analog_write_resolution, 0, arduino_pwm[idx].period);
405-
406-
if (((uint32_t)value) > arduino_pwm[idx].period) {
407-
value = arduino_pwm[idx].period;
408-
} else if (value < 0) {
405+
if (value < 0) {
409406
value = 0;
407+
} else if (value > maxInput) {
408+
value = maxInput;
410409
}
411410

411+
const uint32_t pulse = map(value, 0, maxInput, 0, arduino_pwm[idx].period);
412+
412413
/*
413414
* A duty ratio determines by the period value defined in dts
414415
* and the value arguments. So usually the period value sets as 255.
415416
*/
416-
(void)pwm_set_pulse_dt(&arduino_pwm[idx], value);
417+
(void)pwm_set_pulse_dt(&arduino_pwm[idx], pulse);
417418
}
418419

419420
#endif
420421

421422
#ifdef CONFIG_DAC
423+
static bool dac_channel_initialized[NUM_OF_DACS];
424+
422425
void analogWrite(enum dacPins dacName, int value) {
426+
int ret;
427+
423428
if (dacName >= NUM_OF_DACS) {
424429
return;
425430
}
426431

427-
dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]);
432+
if (!dac_channel_initialized[dacName]) {
433+
ret = dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]);
434+
if (ret != 0) {
435+
return;
436+
}
437+
dac_channel_initialized[dacName] = true;
438+
}
428439

429440
const int max_dac_value = (1U << dac_ch_cfg[dacName].resolution) - 1;
430-
dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id,
431-
map(value, 0, 1 << _analog_write_resolution, 0, max_dac_value));
441+
442+
ret = dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id,
443+
map(value, 0, 1 << _analog_write_resolution, 0, max_dac_value));
444+
445+
if (ret != 0) {
446+
return;
447+
}
432448
}
433449
#endif
434450

0 commit comments

Comments
 (0)