Skip to content

Commit dc6c6f7

Browse files
committed
core: 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 97619da commit dc6c6f7

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

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
@@ -417,15 +421,36 @@ void analogWrite(pin_size_t pinNumber, int value) {
417421

418422
#ifdef CONFIG_DAC
419423
void analogWrite(enum dacPins dacName, int value) {
424+
#if DT_PROP_LEN_OR(DT_PATH(zephyr_user), dac_channels, 0) > 0
425+
const int maxInput = BIT(_analog_write_resolution) - 1U;
426+
int ret = 0;
427+
420428
if (dacName >= NUM_OF_DACS) {
421429
return;
422430
}
423431

424-
dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]);
432+
if (!dac_channel_initialized[dacName]) {
433+
if (!device_is_ready(dac_dev)) {
434+
return;
435+
}
425436

426-
const int max_dac_value = 1U << dac_ch_cfg[dacName].resolution;
427-
dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id,
428-
map(value, 0, 1 << _analog_write_resolution, 0, max_dac_value));
437+
ret = dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]);
438+
if (ret != 0) {
439+
return;
440+
}
441+
dac_channel_initialized[dacName] = true;
442+
}
443+
444+
value = CLAMP(value, 0, maxInput);
445+
446+
const int max_dac_value = BIT(dac_ch_cfg[dacName].resolution) - 1;
447+
const uint32_t output = map(value, 0, maxInput, 0, max_dac_value);
448+
449+
(void)dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id, output);
450+
#else
451+
ARG_UNUSED(dacName);
452+
ARG_UNUSED(value);
453+
#endif
429454
}
430455
#endif
431456

0 commit comments

Comments
 (0)