Skip to content

Commit 0795a5f

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 18d7fac commit 0795a5f

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
@@ -119,7 +119,10 @@ void analogReadResolution(int bits);
119119
#define DAC_ENUMS(n, p, i) DAC##i = i,
120120

121121
enum dacPins {
122-
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), dac_channels, DAC_ENUMS) NUM_OF_DACS
122+
#if DT_NODE_HAS_PROP(DT_PATH(zephyr_user), dac_channels)
123+
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), dac_channels, DAC_ENUMS)
124+
#endif
125+
NUM_OF_DACS
123126
};
124127

125128
#endif

cores/arduino/zephyrCommon.cpp

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

191+
#if DT_NODE_HAS_PROP(DT_PATH(zephyr_user), dac_channels)
191192
static const struct dac_channel_cfg dac_ch_cfg[] = {
192193
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), dac_channels, DAC_CHANNEL_DEFINE)};
193194

195+
static bool dac_channel_initialized[NUM_OF_DACS];
196+
#endif
197+
194198
#endif
195199

196200
#endif // CONFIG_DAC
@@ -339,15 +343,36 @@ void analogWrite(pin_size_t pinNumber, int value) {
339343

340344
#ifdef CONFIG_DAC
341345
void analogWrite(enum dacPins dacName, int value) {
346+
#if DT_NODE_HAS_PROP(DT_PATH(zephyr_user), dac_channels)
347+
const int maxInput = BIT(_analog_write_resolution) - 1U;
348+
int ret = 0;
349+
342350
if (dacName >= NUM_OF_DACS) {
343351
return;
344352
}
345353

346-
dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]);
354+
if (!dac_channel_initialized[dacName]) {
355+
if (!device_is_ready(dac_dev)) {
356+
return;
357+
}
347358

348-
const int max_dac_value = 1U << dac_ch_cfg[dacName].resolution;
349-
dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id,
350-
map(value, 0, 1 << _analog_write_resolution, 0, max_dac_value));
359+
ret = dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]);
360+
if (ret != 0) {
361+
return;
362+
}
363+
dac_channel_initialized[dacName] = true;
364+
}
365+
366+
value = CLAMP(value, 0, maxInput);
367+
368+
const int max_dac_value = BIT(dac_ch_cfg[dacName].resolution) - 1;
369+
const uint32_t output = map(value, 0, maxInput, 0, max_dac_value);
370+
371+
(void)dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id, output);
372+
#else
373+
ARG_UNUSED(dacName);
374+
ARG_UNUSED(value);
375+
#endif
351376
}
352377
#endif
353378

0 commit comments

Comments
 (0)