1 /*
2 * Copyright (c) 2022 Espressif Systems (Shanghai) Co., Ltd.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #define DT_DRV_COMPAT espressif_esp32_dac
8
9 #include <soc.h>
10 #include <zephyr/device.h>
11 #include <zephyr/drivers/dac.h>
12 #include <zephyr/drivers/clock_control.h>
13 #include <hal/rtc_io_types.h>
14 #include <hal/rtc_io_hal.h>
15 #include <hal/rtc_io_ll.h>
16 #include <hal/dac_hal.h>
17 #include <hal/dac_types.h>
18 #include "driver/dac_common.h"
19
20 #include <zephyr/logging/log.h>
21 LOG_MODULE_REGISTER(esp32_dac, CONFIG_DAC_LOG_LEVEL);
22
23 struct dac_esp32_config {
24 int irq_source;
25 const struct device *clock_dev;
26 clock_control_subsys_t clock_subsys;
27 };
28
dac_esp32_write_value(const struct device * dev,uint8_t channel,uint32_t value)29 static int dac_esp32_write_value(const struct device *dev,
30 uint8_t channel, uint32_t value)
31 {
32 ARG_UNUSED(dev);
33
34 dac_output_voltage(channel, value);
35
36 return 0;
37 }
38
dac_esp32_channel_setup(const struct device * dev,const struct dac_channel_cfg * channel_cfg)39 static int dac_esp32_channel_setup(const struct device *dev,
40 const struct dac_channel_cfg *channel_cfg)
41 {
42 ARG_UNUSED(dev);
43
44 if (channel_cfg->channel_id > DAC_CHANNEL_MAX) {
45 LOG_ERR("Channel %d is not valid", channel_cfg->channel_id);
46 return -EINVAL;
47 }
48
49 dac_output_enable(channel_cfg->channel_id);
50
51 return 0;
52 }
53
dac_esp32_init(const struct device * dev)54 static int dac_esp32_init(const struct device *dev)
55 {
56 const struct dac_esp32_config *cfg = dev->config;
57
58 if (!cfg->clock_dev) {
59 LOG_ERR("Clock device missing");
60 return -EINVAL;
61 }
62
63 if (!device_is_ready(cfg->clock_dev)) {
64 LOG_ERR("Clock device not ready");
65 return -ENODEV;
66 }
67
68 if (clock_control_on(cfg->clock_dev,
69 (clock_control_subsys_t) &cfg->clock_subsys) != 0) {
70 LOG_ERR("DAC clock setup failed (%d)", -EIO);
71 return -EIO;
72 }
73
74 return 0;
75 }
76
77 static const struct dac_driver_api dac_esp32_driver_api = {
78 .channel_setup = dac_esp32_channel_setup,
79 .write_value = dac_esp32_write_value
80 };
81
82 #define ESP32_DAC_INIT(id) \
83 \
84 static const struct dac_esp32_config dac_esp32_config_##id = { \
85 .irq_source = DT_INST_IRQN(id), \
86 .clock_dev = DEVICE_DT_GET(DT_INST_CLOCKS_CTLR(id)), \
87 .clock_subsys = (clock_control_subsys_t) DT_INST_CLOCKS_CELL(id, offset), \
88 }; \
89 \
90 DEVICE_DT_INST_DEFINE(id, \
91 &dac_esp32_init, \
92 NULL, \
93 NULL, \
94 &dac_esp32_config_##id, \
95 POST_KERNEL, \
96 CONFIG_DAC_INIT_PRIORITY, \
97 &dac_esp32_driver_api);
98
99 DT_INST_FOREACH_STATUS_OKAY(ESP32_DAC_INIT);
100