Skip to content

Commit e0e5e23

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 e9b9a3b commit e0e5e23

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
@@ -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_PROP_LEN_OR(DT_PATH(zephyr_user), dac_channels, 0) > 0
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_PROP_LEN_OR(DT_PATH(zephyr_user), dac_channels, 0) > 0
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
@@ -342,15 +346,36 @@ void analogWrite(pin_size_t pinNumber, int value) {
342346

343347
#ifdef CONFIG_DAC
344348
void analogWrite(enum dacPins dacName, int value) {
349+
#if DT_PROP_LEN_OR(DT_PATH(zephyr_user), dac_channels, 0) > 0
350+
const int maxInput = BIT(_analog_write_resolution) - 1U;
351+
int ret = 0;
352+
345353
if (dacName >= NUM_OF_DACS) {
346354
return;
347355
}
348356

349-
dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]);
357+
if (!dac_channel_initialized[dacName]) {
358+
if (!device_is_ready(dac_dev)) {
359+
return;
360+
}
350361

351-
const int max_dac_value = 1U << dac_ch_cfg[dacName].resolution;
352-
dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id,
353-
map(value, 0, 1 << _analog_write_resolution, 0, max_dac_value));
362+
ret = dac_channel_setup(dac_dev, &dac_ch_cfg[dacName]);
363+
if (ret != 0) {
364+
return;
365+
}
366+
dac_channel_initialized[dacName] = true;
367+
}
368+
369+
value = CLAMP(value, 0, maxInput);
370+
371+
const int max_dac_value = BIT(dac_ch_cfg[dacName].resolution) - 1;
372+
const uint32_t output = map(value, 0, maxInput, 0, max_dac_value);
373+
374+
(void)dac_write_value(dac_dev, dac_ch_cfg[dacName].channel_id, output);
375+
#else
376+
ARG_UNUSED(dacName);
377+
ARG_UNUSED(value);
378+
#endif
354379
}
355380
#endif
356381

0 commit comments

Comments
 (0)