Skip to content

Commit bce8d7c

Browse files
committed
cores: arduino: analogWrite: Fix DAC output calculation
- Correct max value calculation - Add guard for DAC entry is not defined case - initialize only if DAC not initialized Signed-off-by: TOKITA Hiroshi <tokita.hiroshi@gmail.com>
1 parent cd3f6e1 commit bce8d7c

2 files changed

Lines changed: 33 additions & 5 deletions

File tree

cores/arduino/Arduino.h

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,10 @@ void analogReadResolution(int bits);
118118
#define DAC_ENUMS(n, p, i) DAC##i = i,
119119

120120
enum dacPins {
121-
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), dac_channels, DAC_ENUMS) NUM_OF_DACS
121+
#if DT_PROP_LEN_OR(DT_PATH(zephyr_user), dac_channels, 0) > 0
122+
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), dac_channels, DAC_ENUMS)
123+
#endif
124+
NUM_OF_DACS
122125
};
123126

124127
#endif

cores/arduino/zephyrCommon.cpp

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -190,9 +190,13 @@ static const struct device *const dac_dev = DEVICE_DT_GET(DAC_NODE);
190190
.buffered = true, \
191191
},
192192

193+
#if DT_PROP_LEN_OR(DT_PATH(zephyr_user), dac_channels, 0) > 0
193194
static const struct dac_channel_cfg dac_ch_cfg[] = {
194195
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), dac_channels, DAC_CHANNEL_DEFINE)};
195196

197+
static bool dac_channel_initialized[NUM_OF_DACS];
198+
#endif
199+
196200
#endif
197201

198202
#endif // CONFIG_DAC
@@ -421,15 +425,36 @@ void analogWrite(pin_size_t pinNumber, int value) {
421425

422426
#ifdef CONFIG_DAC
423427
void analogWrite(enum dacPins dacName, int value) {
428+
#if DT_PROP_LEN_OR(DT_PATH(zephyr_user), dac_channels, 0) > 0
429+
const int maxInput = BIT(_analog_write_resolution) - 1U;
430+
int ret = 0;
431+
424432
if (dacName >= NUM_OF_DACS) {
425433
return;
426434
}
427435

428-
dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]);
436+
if (!dac_channel_initialized[dacName]) {
437+
if (!device_is_ready(dac_dev)) {
438+
return;
439+
}
429440

430-
const int max_dac_value = 1U << dac_ch_cfg[dacName].resolution;
431-
dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id,
432-
map(value, 0, 1 << _analog_write_resolution, 0, max_dac_value));
441+
ret = dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]);
442+
if (ret != 0) {
443+
return;
444+
}
445+
dac_channel_initialized[dacName] = true;
446+
}
447+
448+
value = CLAMP(value, 0, maxInput);
449+
450+
const int max_dac_value = BIT(dac_ch_cfg[dacName].resolution) - 1;
451+
const uint32_t output = map(value, 0, maxInput, 0, max_dac_value);
452+
453+
(void)dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id, output);
454+
#else
455+
ARG_UNUSED(dacName);
456+
ARG_UNUSED(value);
457+
#endif
433458
}
434459
#endif
435460

0 commit comments

Comments
 (0)