1 /*
2 * Copyright (c) 2020 Libre Solar Technologies GmbH
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr.h>
8 #include <sys/printk.h>
9 #include <drivers/dac.h>
10
11 #define ZEPHYR_USER_NODE DT_PATH(zephyr_user)
12
13 #if (DT_NODE_HAS_PROP(ZEPHYR_USER_NODE, dac) && \
14 DT_NODE_HAS_PROP(ZEPHYR_USER_NODE, dac_channel_id) && \
15 DT_NODE_HAS_PROP(ZEPHYR_USER_NODE, dac_resolution))
16 #define DAC_NODE DT_PHANDLE(ZEPHYR_USER_NODE, dac)
17 #define DAC_CHANNEL_ID DT_PROP(ZEPHYR_USER_NODE, dac_channel_id)
18 #define DAC_RESOLUTION DT_PROP(ZEPHYR_USER_NODE, dac_resolution)
19 #else
20 #error "Unsupported board: see README and check /zephyr,user node"
21 #define DAC_NODE DT_INVALID_NODE
22 #define DAC_CHANNEL_ID 0
23 #define DAC_RESOLUTION 0
24 #endif
25
26 static const struct device *dac_dev = DEVICE_DT_GET(DAC_NODE);
27
28 static const struct dac_channel_cfg dac_ch_cfg = {
29 .channel_id = DAC_CHANNEL_ID,
30 .resolution = DAC_RESOLUTION
31 };
32
main(void)33 void main(void)
34 {
35 if (!device_is_ready(dac_dev)) {
36 printk("DAC device %s is not ready\n", dac_dev->name);
37 return;
38 }
39
40 int ret = dac_channel_setup(dac_dev, &dac_ch_cfg);
41
42 if (ret != 0) {
43 printk("Setting up of DAC channel failed with code %d\n", ret);
44 return;
45 }
46
47 printk("Generating sawtooth signal at DAC channel %d.\n",
48 DAC_CHANNEL_ID);
49 while (1) {
50 /* Number of valid DAC values, e.g. 4096 for 12-bit DAC */
51 const int dac_values = 1U << DAC_RESOLUTION;
52
53 /*
54 * 1 msec sleep leads to about 4 sec signal period for 12-bit
55 * DACs. For DACs with lower resolution, sleep time needs to
56 * be increased.
57 * Make sure to sleep at least 1 msec even for future 16-bit
58 * DACs (lowering signal frequency).
59 */
60 const int sleep_time = 4096 / dac_values > 0 ?
61 4096 / dac_values : 1;
62
63 for (int i = 0; i < dac_values; i++) {
64 ret = dac_write_value(dac_dev, DAC_CHANNEL_ID, i);
65 if (ret != 0) {
66 printk("dac_write_value() failed with code %d\n", ret);
67 return;
68 }
69 k_sleep(K_MSEC(sleep_time));
70 }
71 }
72 }
73